美文网首页
react父子组件相互传参

react父子组件相互传参

作者: tenro | 来源:发表于2020-06-10 17:59 被阅读0次

    父组件传子: props

    class Son extends Component{
          render(){
                return (
                      <div>
                            <h1>{ this.props.msgOfDad }</h1>
                      </div>
                )
          }
    }
    
    class Dad extends Component{
          render(){
                let data = 'i am a message from dad'
                return (
                      <Son msgOfDad={ data } />
                )
          }
    }
    
    ReactDOM.render(
        <App/>
        document.querySelector("#app')
    )
    

    子传父:使用回调函数

    class Son extends Component{
          render(){
                return (
                        //通过 this.props将父组件的绑定在子组件上
                       <input type="text" onChange={ (e) => this.props.handleChange(e.target.value) }
                )
          }
    }
    
    class Dad extends Component{
          constructor(props) {
                super(props)
                this.state = {
                      data: ''
                }
          }
          //子组件触发事件将调用该函数
          handleChange = text => {
                this.setState({
                      data: text
                })
          }
          render(){
                return (
                      <div>
                            <p>This message is from Child: { this.state.data }</p>
                            <Son handleChange = { this.handleChange } />
                      </div>
                )
          }
    }
    
    ReactDOM.render(
        <App/>
        document.querySelector("#app')
    )
    

    相关文章

      网友评论

          本文标题:react父子组件相互传参

          本文链接:https://www.haomeiwen.com/subject/yovptktx.html