加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React:将子状态传递给父状态

发布时间:2020-12-15 20:49:46 所属栏目:百科 来源:网络整理
导读:我和React工作了一年多,我读过 Thinking in react,Lifting state up和 State and lifecycle. 我了解到React的数据流概??念是单向数据流. 来自这些页面的Citates: React’s one-way data flow (also called one-way binding) keeps everything modular and f
我和React工作了一年多,我读过 Thinking in react,Lifting state up和 State and lifecycle.

我了解到React的数据流概??念是单向数据流.

来自这些页面的Citates:

React’s one-way data flow (also called one-way binding) keeps everything modular and fast.

Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand,so follow these steps to figure it out:…

If you imagine a component tree as a waterfall of props,each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

据我所知,不允许使用以下示例,因为我将子状态数据传递给父级.但我看到一些开发人员这样工作:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { fromParent: null };
    }

    addSomething(stateValueFromChild) {
        this.setState({fromParent: stateValueFromChild});
    }

    render() {
        return <Child
                addSomething={(stateValueFromChild) => this.addSomething(stateValueFromChild)}>
                 // ...
        </Child>;
    }
}

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = { fromChild: 'foo' };
    }

    render() {
        return <Form onSubmit={() => this.props.addSomething(this.state.fromChild)}>
                 // ...
        </Form>;
    }
}

我现在的问题是:

>这真的不允许吗?
>为什么这不是模块化和快速的?
>这是否真的制动了单向数据流,成为双向数据流?
>这种方式可能会发生什么其他问题?
>当我举起国家时,你会如何解决以下案件; 50个使用该子组件的具体父级,是否每个父级对于他们使用的同一个孩子具有相同的初始化子状态?

这是允许的,你的代码没有任何问题,但是我不会把它称为从子节点传递到父节点.你所做的就是调用在props中传递的方法,并通过一些参数触发事件,在你的例子中是一个参数,但它可以是任何其他变量.父组件对此参数的性质一无所知,它只接收值并能够对其执行任何操作,例如将其自身状态更改为另一个.如果Child的状态将更改,则在没有再次触发onSubmit事件的情况下,Parent将不会收到此更新.但是,当道具发生变化时,孩子们总是从父母那里收到更新并自动获得重新渲染.当然,一些道具可能是一些父母的状态.这是行为的主要区别.

有一篇很好的文章详细解释了这一点:Props down,Events Up

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读