繁体   English   中英

我可以在其父级的反应组件中设置子级道具吗?

[英]Can I set the children props in a react component from its parent?

是否有可能做出这样的反应:

var App = React.createClass({
    getInitialState: function(){
        return {
            children: [<div/>, <div/>],
            comp: ''
        };
    },
    componentWillMount: function(){
        this.setState({
            comp: <SomeComponent children={this.state.children}/>
        });
    },
    render: function(){
        return (
            <div>
                {this.state.comp === '' ? this.state.children : this.state.comp}
            </div>
        );
    }
});

当我尝试做类似的事情时,我得到: Uncaught TypeError: Cannot read property '_currentElement' of null所以我假设答案是否定的,但我认为必须有某种方式考虑

<SomeComponent>
    <div/>
</SomeComponet>

其中<SomeCompent/>呈现一个<div/> ,是有效的。 但是,在这种特殊情况下,我会遇到同样的错误,但是如果您查看 React-Bootstrap https://react-bootstrap.github.io/ 之类的内容,则必须是可能的。

为什么要将 html 标签作为状态传递? 我并不是说不好,但总有更好的解决方案来解决您的问题。 假设一个子组件将状态布尔值 true 或 false 传递给父组件( Flux - 子组件传递到存储的动作,父组件可以通过 onChange 事件获取状态)。 有了它,您可以调用父元素来呈现不同的视图。

_onChange: function() {
    this.setState(this._getStateFromStores());
},

render: function() {
    var view;

    if (this.state.childAction) {
        view = <SomethingTrue/> ;
    }
    if (!this.state.childAction) {
        view = <SomethingFalse/> ;
    }

    return (
        <div>
            {view}
        </div>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM