父向子传参
父组件向子组件传参时用属性的方式传递
子组件接收的时候用props调用
子组件不能直接改父组件的变量值
- 父组件实例如下:
import React,{Component,Fragment}from 'react'
import TodoItemList from './TodoItemList'
class TodoList extends Component{
constructor(poprs){
super(poprs);
this.state={
inputValue:'',
list:['学习英文','学习数字']
}
}
render(){
return (
<Fragment>
<div>
<input type="text"
value={this.state.inputValue}
onChange={this.handleInputChange.bind(this)}
/>
<button onClick={this.handleButtonClick.bind(this)}>提交</button>
</div>
<ul>
{
this.state.list.map((item,index)=>{
// 父传子 属性传输
return (
<TodoItemList
key={index}
item={item}
index={index}
DelItem={this.handleDelList.bind(this)}
>
</TodoItemList>
)
})
}
</ul>
</Fragment>
)
}
handleInputChange(e){
this.setState({
inputValue:e.target.value
})
}
handleButtonClick(){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
handleDelList(index){
var list=[...this.state.list]
list.splice(index,1)
this.setState({
list:list
})
}
}
export default TodoList;
- 子组件实例如下:
import React,{Component,Fragment}from 'react'
class TodoItemList extends Component{
constructor(props){
super(props)
}
render(){
return(
<Fragment>
<div onClick={this.handleItemClick.bind(this)}>{this.props.item}</div>
</Fragment>
)
}
handleItemClick(){
const {DelItem,index}=this.props
DelItem(index)
}
}
export default TodoItemList