簡體   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