父组件传递子组件
常规的数据传递方式就是父传子,子组件直接通过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> ); } }原文链接:https://www.f2er.com/react/303101.html