react视频笔记2

版权声明:版权所有!转载通知我! https://blog.csdn.net/qq_41775119/article/details/83050812

组件写完记得导出

export default TodoItem;

在别的组件里引入TodoItem组件

import TodoItem from './TodoItem';

在return中就可以取代之前那一串JSX <div>的代码

return(
<TodoItem />)
//如果有多个东西则用一个<div>包裹起来

TodoItem组件文件中:

要进行灵活的内容传递

即【父组件向子组件传递数据】

//TodoList中
return(
<div>
  <TodoItem content={item}/>

//TodoItem中
render(){
return <div>{this.props.content}</div> 
}

【子调用父组件方法修改父组件】

constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);//绑定方法二 更好 节约性能
}

render(){
return (//绑定方法一:
<div onClick={this.handleClick.bind(this)}>//如果只是一个函数,this会指向不明,所以需要绑定
   {this.props.content}
</div>)
}
          

)

handleClick(){

}

//TodoList中我们还需要传给子组件index值
<ul>
{
this.state.list.map((item,index)=>{
return(
<div>
<TodoItem index={index} content={item} />
</div>
)

想要调用父组件方法需要将父组件方法传递给子组件

return(
<div>
<TodoItem
handleID={this.handleItemDelete}
/>
</div>

//TodoItem.js中

handleClick(){
this.props.handleID(this.props.index)
}

但是报错了

原因是这个this指向的不是父组件(方法是父组件的方法)

解决方法:

扫描二维码关注公众号,回复: 3726212 查看本文章
<ul>
{
this.state.list.map((item,index)=>{
return (
<div>
<TodoItem
content={item}
index={index}
handleID={this.handleItemDelete.bind(this)}//绑定完毕~
/>
</div>

优化:

this.props.content=const content ={ this. props}; 以后用content直接代替这一串

onchange={this.handleInputChange.bind(this) //直接写在属性里影响性能

//修改

this.handleInputChange = this.handleInputChange.bind(this); 替换掉原来的 放在constructor下面

把画界面中的逻辑相关代码专门弄到新的函数里

getTodoItem(){
return this.state.list.map((item,index)=>{
return(
<div>
<TodoItem 
    index={index} 
    content={item}
    deleteItem={this.handleItemDelete} />
</div>
)
})
}

 在之前的位置

<ul>
 {this.getTodoItem()}
</ul>

//旧版写法:

this.setState({
inputValue:e.target.value
})

//新版写法:
this.setState (() => ({
{ 
inputValue: e.target.value
}
}))
}

猜你喜欢

转载自blog.csdn.net/qq_41775119/article/details/83050812