react组件之间的传值

1 父=>子

在子组件标签上绑定父组件要传递的数据,子组件内部通过this.props进行接收

父组件代码

import React from 'react'
import Child from './child'

class Parents extends React.Component{
    state={
        msg:'你好,我是父组件的数据'
    }
    render(){
        return(
            <div>
                <h1>父组件</h1>
                <button type="button" onClick={()=>this.toChild()}>button</button>
                <p>{this.state.msg}</p>
                <Child msg={this.state.msg}/>
            </div>
        )

    }
    toChild(){
        this.setState({
            msg:"改变数据"
        })
    }
}
export default Parents;

子组件代码

import React from 'react'
class Child extends React.Component{
    render(){
        return(
            <div>
                <h1>子组件</h1>
                <p>接收父组件的数据:---{this.props.msg}</p>
            </div>
        )
    }
}
export default Child;

2.子=>父

1.父组件提供一个函数,用于接收数据

2.父组件把这个函数传递给子组件(最好把this绑定到父组件上面)

3.子组件内部通过this.props进行调用并传值

父组件代码

import React from 'react'
import Child from './child'

class Parents extends React.Component{
    state={
        msg:''
    }
    render(){
        return(
            <div>
                <h1>父组件</h1>
                <p>接收子组件的数据--{this.state.msg}</p>
                <Child getMessage={this.getMessage.bind(this)}/>
            </div>
        )
    }
    getMessage(msg){
        this.setState({
            msg:msg
        })
    }
}
export default Parents;

子组件代码

import React from 'react'
class Child extends React.Component{
    state={
        msg:"这是子组件的数据"
    }
    render(){
        return(
            <div>
                <h1>子组件</h1>
                <button type="button" onClick={()=>this.toparent()}>button</button>
            </div>
        )
    }
    toparent(){
        this.props.getMessage(this.state.msg)
    }
}
export default Child;

3.非父子的话 如果是平行 就子1->父->子2,如果嵌套复杂的话 就要用状态管理了 这里就不多介绍了

扫描二维码关注公众号,回复: 10569569 查看本文章
发布了109 篇原创文章 · 获赞 23 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/xy19950125/article/details/97787022