在React中,父如何以编程方式更改另一个组件上的prop或state值?

时间:2016-08-05 12:58:27

标签: javascript reactjs

我创建并渲染了另一个组件。单击按钮,我想进行一些计算,然后更改其他组件上的一些道具,以便更新其视图。我该怎么做?

如果他们需要是状态值而不是道具,那就没关系。可以从另一个组件调用setState()吗?

class MainComponent extends React.Component {

    other: null,

    constructor(props, children)
    {
        //Create the component
        this.other = ReactDOM.render( otherReactElement, document.body );
    }

...

    //An on Click handler
    handle: function(evt)
    {
        //This is what I want to do
        other.setProps( { aPropToChange: "new value" } );
    }
};

" setProps"已弃用。我还能做些什么来启用类似的东西?

2 个答案:

答案 0 :(得分:1)

如果您想将新道具传递给other,则必须使用新道具再次致电ReactDOM.render(),因为您可以看到here

我创建了jsfiddle,您可以在其中查看如何正确更新propsstate

class MainComponent extends React.Component {

    constructor(props)
    {
        super(props);
        this.other = ReactDOM.render( <Hello name="World"/>, document.getElementById('otherComponent') );
    }
    changeState(evt)
    {
        this.other.setState({lastName: "setState works"})
    }
    changeProps(evt){
        this.other = ReactDOM.render( <Hello name="New Name" /> , document.getElementById('otherComponent') );
    }
    render(){
        return <div>
            <button onClick={this.changeState.bind(this)}>Change state</button>
            <button onClick={this.changeProps.bind(this)}>Change props</button>
            </div>
    }
};

答案 1 :(得分:1)

在React中,父组件可以使用refs更改其子组件的状态。使用refs,您可以获得对子组件的引用,并且可以使用该引用来调用子组件内的函数,并且该函数可以在其中调用setState()。

您可以在此处详细了解react refs:https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute