react数据流

1.react数据流以及组件间沟通

react是自上而下的单向数据流,从父节点传递到子节点(通过props);如果顶层的props改变,react会重新渲染所有子节点。

props:用于组件间状态的传递,用于整个组件树中传递数据和配置,在当前组件访问props使用this.props;

state 指的是组件内部的状态,只能从当前组件调用this.setState修改state值,一般更新子组件都是通过改变state值,更新新子组件的props值而得到更新。

组件沟通

  • 父子组件沟通
    • 父组件传递数据给子组件
      通过传递props即可实现。
class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            msg: 'haha'
        }
    }

    componentDidMount(){
        setTimeout(() => {
            this.setState({
                msg: 'xixi'
            })
        },1000)
    }

    render(){
        return (
            <Child msg = {this.state.msg} />
        );
    }
}

class Child extends React.Component {
    constructor(props) {
        super(props);
    }
    render(){
        return <div>{this.props.msg}</div>
    }
}

如果父组件个子组件之间不止一个层级,那么通过 …将父组件的信息传递给更深层级的子组件。

  • 子组件传递数据给父组件
    子组件向父组件通信同样需要用props,父组件传递一个函数给子组件,子组件调用函数。
class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            msg: 'haha'
        }
    }

    passMsg(msg){
        this.setState({
            msg: msg
        })
    }
    render(){
        return <Child passMsg = {msg => this.passMsg(msg)}/>
    }
}

class Child extends React.Component{
    constructor(props) {
        super(props)
    }
    componentDidMount(){
        setTimeout(() => {
            this.props.passMsg('xixi')
        },1000)
    }
    render(){
        return <div>子组件向父组件通信</div>
    }
}

使用箭头函数 将父组件的passMsg通过props传递给子组件,主要是箭头函数保证了子组件调用函数的时候,函数内部的this仍然指向父组件。

  • 对于兄弟组件之间的通信
    他们拥有共同的父组件,所以1先向父组件通信,父组件再向2通信,从而实现1和2之间的通信
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值