React父子組件通信,父組件向子組件傳值晤揣,子組件改變父組件數(shù)據(jù)桥爽。
1.父組件TodoList
- 在
getItems()
函數(shù)中調(diào)用子組件- 通過屬性的形式向子組件傳值
content={value}
- 向子組件傳遞方法
delFunc={this.handleDelItemClick}
和index={index}
,改變list
數(shù)組 昧识。- 別忘記在
constructor
中修改this
的指向了this.handleDelItemClick = this.handleDelItemClick.bind(this)
钠四。
import React , { Component, Fragment } from 'react'
import TodoItem from './TodoItem'
class TodoList extends Component {
// constructor 在組件創(chuàng)建的第一個(gè)時(shí)刻自動(dòng)被執(zhí)行
constructor (props) {
super(props)
this.handleDelItemClick = this.handleDelItemClick.bind(this)
// 在組件中創(chuàng)建了兩個(gè)數(shù)據(jù),數(shù)據(jù)一定要定義在state中
this.state = {
inputValue: '',
list: [
'hello1', 'hello2', 'lell3'
]
}
}
handleInputChange (e) {
// bind修改this的指向當(dāng)前的組件
console.log(e.target.value)
// this.state.inputValue = e.target.value // 這是錯(cuò)誤的?
// 改變state的數(shù)據(jù) 調(diào)用函數(shù)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('點(diǎn)擊每一項(xiàng)--', index);
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list
})
}
getItems () {
/**
* 父子組件跪楞,
* 父組件通過屬性的形式向子組件傳值缀去。
* 父組件向子組件傳遞方法時(shí),注意作用域的變更甸祭。
* */
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='請(qǐng)輸入內(nèi)容'
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內(nèi)接受父組件傳遞過來的值缕碎。
this.props.xxxxx
- 點(diǎn)擊事件調(diào)用函數(shù)注意修改
this
的指向。用bind
修改指向- 要改變父組件的值池户,調(diào)用父組件傳遞過來的方法
delFuc(index)
import React, { Component } from 'react'
class TodoItem extends Component {
constructor (props) {
super(props)
this.handleDelItemClick = this.handleDelItemClick.bind(this)
}
handleDelItemClick () {
/* 調(diào)用父組件的方法咏雌,在父組件中改變list數(shù)據(jù) */
// this.props.delFunc(this.props.index)
/* 簡化,解構(gòu)賦值 */
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