這里通過todolist的功能來說明
父組件:
import React,{ Component,Fragment } from 'react';
import TodoItem from './ToDoItem';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
todoList: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeInput = this.handleChangeInput.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.parentMethod = this.parentMethod.bind(this);
this.testChildren = this.testChildren.bind(this);
}
render() {
const { inputValue,todoList } = this.state;
return (
<Fragment>
<p><input value={inputValue} onChange={this.handleChangeInput} /><button onClick={this.handleSubmit} type="button">提交</button></p>
<TodoItem ref="children" parentMethod = {this.parentMethod} />
<button onClick={this.testChildren}>測試調用子組件的方法</button>
<ul>
{
todoList.map((item,index) => (
<li
key={+new Date() + index}
dangerouslySetInnerHTML={{__html:item}}
onClick={() => this.handleDelete(index)}></li>
))
}
</ul>
</Fragment>
)
};
parentMethod() {
alert("調動父組件方法");
}
testChildren() {
this.refs.children.childrenMethod();
}
handleChangeInput(e) {
this.setState({
inputValue: e.target.value
},() => {
console.log(this.state);
})
}
handleSubmit() {
this.setState({
todoList: [...this.state.todoList,this.state.inputValue],
inputValue: '',
})
}
handleDelete(index) {
// immutable概念
// state不允許我們做任何的改變
let list = [...this.state.todoList]; //拷貝一份TodoList
list.splice(index,1);
this.setState({
todoList: list
})
}
}
export default TodoList;
子組件
import React,{ Component } from 'react';
class TodoItem extends Component {
constructor(props) {
super(props);
this.childrenMethod = this.childrenMethod.bind(this);
}
render() {
return (
<div>
<h3>子組件</h3>
<button onClick={this.childrenMethod}>子組件方法</button>
<button onClick={this.props.parentMethod}>父組件方法</button>
</div>
)
}
childrenMethod() {
alert("調用子組件方法");
}
}
export default TodoItem;
總結:
父組件給子組件傳遞數據:直接在調用子組件的地方傳遞數據即可。
調用子組件的方法:簡單說就是給子組件,通過ref起個名字,然后在父組件的點擊事件中,通過this.refs.子組件的名字.子組件的方法來實現
子組件調用父組件的方法。在調用子組件的地方將方法傳遞,子組件中通過this.props。父組件傳遞的方法即可
子組件給父組件傳遞數據:通過調用父組件的方法時,通過callback回調傳遞數據。this.props.父組件的方法(傳遞的數據)
