React组件间传值
React父组件向子组件传值
父组件通过属性的方式向子组件传递参数
子组件通过props接受父组件传递过来的参数
父组件
render() {
return (
<div>
<ul>
{
//通过conten传递item
this.state.list.map((item, index) => {
return <TodoItem content={item}/>
})
}
</ul>
</div>
);
}
子组件
render() {
return (
//通过props接受content中的参数
<div>{this.props.content}</div>
)
}
React子组件向父组件传值
子组件如果想和父组件进行通信,需要调用父组件传递过来的方法
父组件
//index为子组件传递的
handleDelete(index) {
const list = [...this.state.list];
list.splice(index, 1);
this.setState({list})
}
render() {
return (
<div>
<div>
<input value={this.state.inputValue} onChange={this.handleInputChange.bind(this)}></input>
<button onClick={this.handleBtnClick.bind(this)}>添加</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
//传递给子组件delete方法
return <TodoItem delete={this.handleDelete.bind(this)} key={index} content={item} index={index}/>
})
}
</ul>
</div>
);
}
子组件
//通过props接受父组件的delete方法并进行传递index值
handleDelete() {
this.props.delete(this.props.index);
}
render() {
return (
<div onClick={this.handleDelete.bind(this)}>{this.props.content}</div>
)
}
}
总结
父组件向子组件传值:使用 props
子组件向父组件传值:使用 props 回调