在有状态 React 组件中更改 <select> 值的正确方法
The right way to change a <select> value in a stateful React component
我正在有状态组件中渲染 <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')
);
并且无法弄清楚为什么浏览器用户无法将所选选项更改为 one
。这是 JS Bin.
正如 Felix 已经在评论中暗示的那样,当您将 ES6 类 用于 React 组件时,您不能依赖 React 在正确的上下文中调用回调(如 handleModeSelection
)(已记录 here).
有多种方法可以解决此问题。一个常见的方法是在构造函数中绑定回调:
constructor(props) {
super(props);
this.state = {mode: 'all'};
this.handleModeSelection = this.handleModeSelection.bind(this);
}
我正在有状态组件中渲染 <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')
);
并且无法弄清楚为什么浏览器用户无法将所选选项更改为 one
。这是 JS Bin.
正如 Felix 已经在评论中暗示的那样,当您将 ES6 类 用于 React 组件时,您不能依赖 React 在正确的上下文中调用回调(如 handleModeSelection
)(已记录 here).
有多种方法可以解决此问题。一个常见的方法是在构造函数中绑定回调:
constructor(props) {
super(props);
this.state = {mode: 'all'};
this.handleModeSelection = this.handleModeSelection.bind(this);
}