改变<选择>有状态React组件中的值

The right way to change a <select> value in a stateful React component

本文关键字:组件 React lt 选择 gt 改变 状态      更新时间:2023-09-26

我正在有状态组件中呈现<select>

class StatefulContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {mode: 'all'};
    }
    render() {
        return <div>
            <form>
                <select value={this.state.mode} onChange={this.handleModeSelection}>
                    <option value='all'>Show all</option>
                    <option value='one'>Just the first one</option>
                </select>
            </form>
        </div>;
    }
    handleModeSelection({target: {value}}) {
        this.setState({mode: value});
    }
}
React.render(
    <StatefulContainer/>,
    document.getElementById('root')
);

并且不能弄清楚为什么浏览器用户不可能将所选择的选项更改为CCD_ 2。这是一个JS Bin。

正如Felix已经在评论中暗示的那样,当您为React组件使用ES6类时,您不能依赖React在正确的上下文中调用回调(如handleModeSelection)(此处记录)。

有多种方法可以解决这个问题。一种常见的方法是在构造函数中绑定回调:

constructor(props) {
  super(props);
  this.state = {mode: 'all'};
  this.handleModeSelection = this.handleModeSelection.bind(this);
}