React.js onChange 让父级知道改变的状态

Gal*_*lya 5 javascript onchange parent reactjs

我有一个<select>使用<option>元素渲染的组件。当发生任何更改时,我想更改组件的状态以保持当前选定选项的值。据我所知,我没有任何其他选择来保持这个值,因为 React JS 中的道具必须是不可变的。

当我通知父母更改时,问题就出现了。我使用从handleChangehandleChange函数的回调来做到这一点。所以在子元素中,我实际上调用了该handleChange函数,设置了新状态并调用了回调(父元素handleChange)。但是在父函数中,当我询问 state 属性的值时,我收到了旧的(似乎新的尚未设置)。

那么有什么想法吗?

Fel*_* D. 3

我建议使用单一数据流模式(如FluxReflux)来构建您的 React 应用程序,并避免此类错误和复杂的反向数据流。

根据我对你的问题的理解,如果没有 Flux,你可以做这样的事情。

var React = require("react");

var ParentComponent = React.createClass({
    handleChange: function(newOption){
        console.log("option in child component changed to " + newOption);
    },
    render: function(){
        return (
            <div>
                <ChildComponent handleChange={this.handleChange}/>
            </div>
        )
    }
});

var ChildComponent = React.createClass({
    getInitialState: function(){
        return {
            selectedOption: 0
        };
    },
    handleChange: function(){
        var option = this.refs.select.getDOMNode().value;
        this.setState({ selectedOption: option});
        // I'm passing the actual value as an argument,
        // not this.state.selectedOption
        // If you want to do that, do it in componentDidUpdate
        // then the state will have been set
        this.props.handleChange(option);
    },
    render: function(){
        return (
            <div>
                <h4>My Select</h4>
                {this.state.selectedOption}
                <select ref="select"
                        onChange={this.handleChange}>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                </select>
            </div>
        )
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑 添加了几个被遗忘的分号。这些天我写了太多的 Python 代码。

Edit2 更改了代码。您的问题可能是,如果您使用状态 ( this.state.selectedOption) 中的值调用父级的 handleChange ,则状态尚未设置,因此您必须提供实际值作为参数。如果您确实想使用,请在componentDidUpdatethis.state.selectedOption中调用父级。handleChange