React----react组件传值

react组件传值方式:
(1)父传子:子组件标签定义自定义属性+子组件内部this.props接收
传递:子组件在父组件中当做标签使用时,子组件标签定义自定义属性val,值为需要传递的值<One val={fatherMsg}></One>
接收:子组件内部通过this.props.val进行接收(使用解构赋值能简化代码,将val先解构出来,直接使用)
render(){
    let {val} = this.props
    return (
        <div className="one"><p>one接收到app传递过来的值为:{val}</p></div>
    )
}
(2)子传父:子组件标签定义自定义属性fnName+子组件内部this.props.fnName来触发
传递:子组件内部通过this.props.fnName来触发这个函数,参数通过函数进行传递
render(){
    return (
        <div className="twoSon">
            <button onClick={this.handleClick.bind(this)}>发送给two</button>
        </div>
    )
}
handleClick(){this.props.fnName(this.state.sonMsg)}

接收:子组件在父组件中当做标签使用时,子组件标签定义自定义属性fnName,值为一个函数;最后通过参数进行接收传递过来的数据

render(){
    let {msg} = this.state;
    return (
        <div className="two">
            <p>{msg}</p>
            <TwoSon fnName={this.handleGet.bind(this)}></TwoSon>
        </div>
    )
}
handleGet(val){
    this.setState({msg:'接收到twoSon传递过来的值为:'+val})
}
(3)非父子:手动封装事件订阅$on、$emit;传值组件写事件函数,函数中$emit("fnName",val);接收值componentDidMount声明函数中通过$on("fnName",(val)=>{})来接收val
例如:传值组件:调用 $emit:
render(){
    return (
        <div className="thr"><button onClick={this.handleClick.bind(this)}>发送给fou</button></div>
    )
}
handleClick(){Observer.$emit("fnName",this.state.thrMsg)}

接收组件:调用 $on:

render(){
    return (
        <div className="fou"><p>接收到thr传递过来的值为:{this.state.msg}</p></div>
    )
}
componentDidMount(){
    Observer.$on("fnName",(val)=>{this.setState({msg:val})})
}
原文地址:https://www.cnblogs.com/snowstorm22/p/10559622.html