React學習筆記之父子組件間通信的實現(xiàn):
今天弄清楚了父子組件間通信是怎么實現(xiàn)的。父組件向子組件通信是通過向子組件傳遞參數(shù)props:
// APP.js
return (
<div className='App'>
<h1>我的待辦</h1>
<div className="inputWrapper">
<TodoInput content={this.state.newTodo}
onChange={this.changeTitle.bind(this)}
onSubmit={this.addTodo.bind(this)} />
</div>
<ol className='todoList'>
{todos}
</ol>
</div>
);
changeTitle(event) {
this.setState({
newTodo: event.target.value,
todoList: this.state.todoList
})
}
addTodo(event) {
this.state.todoList.push({
id: idMaker(),
title: event.target.value,
status: null,
deleted: false
})
console.log('addtodo')
this.setState({
newTodo: '',
todoList: this.state.todoList
})
}
// TodoInput.js
export default class TodoInput extends Component {
render() {
return <input type='text' value={this.props.content}
className="TodoInput"
//這里為什么要綁定this呢,因為在事件的回調函數(shù)(
//也就是changeTitle)里,this是指向觸發(fā)事件的目標元素,
//而我們對this有特殊的用途,必須讓this指向子組件本身,
//我們才能取到props里的回調函數(shù),來加以調用。因此必須
//綁定this指向子組件。
onChange={this.changeTitle.bind(this)}
onKeyPress={this.submit.bind(this)}
/>
}
submit(e) {
if (e.key == 'Enter') {
//調用父組件里的onSubmit函數(shù),
//并將事件對象作為參數(shù)傳遞進去
this.props.onSubmit(e)
console.log('enter')
}
}
changeTitle(event) {
this.props.onChange(event)
}
}
父組件中實例化一個子組件時傳遞了參數(shù)content={this.state.newTodo,這是一個字符串this.state = { newTodo: '', todoList: [ ] },這樣實現(xiàn)了父組件向子組件傳遞了參數(shù)。
那么子組件是怎么向父組件通信的呢?父組件向子組件通信是傳遞參數(shù),很自然的如果傳遞的是父組件里定義的回調函數(shù),子組件通過props來調用這個回調函數(shù),也就實現(xiàn)了子組件向父組件通信的目的了。上面的onChange和onSubmit都是父組件向子組件傳遞的props里,而且他們都指向父組件里的changeTitle和addTodo函數(shù),在需要時,子組件就可以通過props調用它們,這樣就實現(xiàn)了子組件向父組件通信的目的。一句話總結:當傳遞數(shù)據(jù)給子組件的props時:
content={this.state.newTodo}
,就是父組件向子組件通信,當傳遞的是回調函數(shù)名給props時:
onChange={this.changeTitle.bind(this)}
,就是子組件向父組件通信。