React父子组件通信,父组件向子组件传值,子组件改变父组件数据。
1.父组件TodoList
- 在
getItems()
函数中调用子组件- 通过属性的形式向子组件传值
content={value}
- 向子组件传递方法
delFunc={this.handleDelItemClick}
和index={index}
,改变list
数组 。- 别忘记在
constructor
中修改this
的指向了this.handleDelItemClick = this.handleDelItemClick.bind(this)
。
import React , { Component, Fragment } from 'react'
import TodoItem from './TodoItem'
class TodoList extends Component {
// constructor 在组件创建的第一个时刻自动被执行
constructor (props) {
super(props)
this.handleDelItemClick = this.handleDelItemClick.bind(this)
// 在组件中创建了两个数据,数据一定要定义在state中
this.state = {
inputValue: '',
list: [
'hello1', 'hello2', 'lell3'
]
}
}
handleInputChange (e) {
// bind修改this的指向当前的组件
console.log(e.target.value)
// this.state.inputValue = e.target.value // 这是错误的❌
// 改变state的数据 调用函数this.setState
this.setState({
inputValue: e.target.value
})
}
handleKeyUp (e) {
console.log(e.keyCode)
if (e.keyCode === 13 && this.state.inputValue) {
const list = [...this.state.list, this.state.inputValue]
this.setState({
list,
inputValue: ''
})
}
}
handleDelItemClick (index) {
console.log('点击每一项--', index);
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list
})
}
getItems () {
/**
* 父子组件,
* 父组件通过属性的形式向子组件传值。
* 父组件向子组件传递方法时,注意作用域的变更。
* */
return (
this.state.list.map((value, index) => {
return (
// <li key={index} onClick={this.handleDelItemClick.bind(this,index)}>
// {value}
// </li>
<TodoItem
key={index}
content={value}
index={index}
delFunc={this.handleDelItemClick}
/>
)
})
)
}
render () {
return (
<Fragment>
<input
placeholder='请输入内容'
value={this.state.inputValue}
onChange={this.handleInputChange.bind(this)}
onKeyUp={this.handleKeyUp.bind(this)}
/>
<ul>
{ this.getItems() }
</ul>
</Fragment>
)
}
}
export default TodoList
2.子组件 TodoItem.js
- 在render内接受父组件传递过来的值。
this.props.xxxxx
- 点击事件调用函数注意修改
this
的指向。用bind
修改指向- 要改变父组件的值,调用父组件传递过来的方法
delFuc(index)
import React, { Component } from 'react'
class TodoItem extends Component {
constructor (props) {
super(props)
this.handleDelItemClick = this.handleDelItemClick.bind(this)
}
handleDelItemClick () {
/* 调用父组件的方法,在父组件中改变list数据 */
// this.props.delFunc(this.props.index)
/* 简化,解构赋值 */
const { delFunc, index } = this.props
delFunc(index)
}
render () {
/* 接收父组件传过来的值 */
const content = this.props.content
// const { content } = this.props
return (
<li onClick={this.handleDelItemClick}>
{content}
</li>
)
}
}
export default TodoItem