父元件傳遞子元件
常規的資料傳遞方式就是父傳子,子元件直接通過this.props來使用。
子元件傳遞父元件
子元件通過父元件的事件方法來傳遞
例如:
父元件:
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
serviceView: []
}
this.setServiceView = this.setServiceView.bind(this);
this.clickAction = this.clickAction.bind(this);
}
/**
* 設定服務檢視資料
*
* @param {[type]} data [description]
*/
setServiceView(data) {
this.setState({
serviceView: data
});
}
clickAction() {
this.refs.timebar.childMethod();
}
render() {
return (
<div>
<button onClick={this.clickAction}></button>
<Timebar ref="timebar" setServiceView={this.setServiceView} ref="timebar" />
<ServiceView treeData={this.state.serviceView} />
</div>
);
}
}
子元件:
export default class Timebar extends Component {
constructor(props) {
super(props);
this.state = {
serviceView = [1, 2];
};
}
childMethod () {
console.log("我是子元件的方法");
}
componentDidMount() {
this.props.setService(this.props.servicew)
}
render() {
return (
<div></div>
);
}
}