React类组件中如何将下拉框选中项设置为组件state?
Hey there! Let's walk through your React component code and clear up those questions you have about syncing the dropdown's selected value to the component state.
First, let's format your original code for better readability:
var Dummy = React.createClass({ onSelect: function(e) { this.setstate({ selectedItem: e.currentTarget.value }) }, render: function() { return ( <select onChange={this.onSelect.bind(this)}> <option value="1">Item 1</option> <option value="2">Item 2</option> <option value="3">Item 3</option> </select> ) } });
First, fix the critical typo
You might have noticed this code doesn't work as expected—this.setstate should be this.setState (capitalize the "S"). React uses camelCase for all its API methods, so the lowercase "s" will throw an error because the method doesn't exist on the component instance.
Is e.currentTarget.value a valid way to get the selected value?
Absolutely! Your approach here is totally reliable:
currentTargetrefers specifically to the element the event listener is attached to (the<select>element in this case). This is rock-solid even if you're using event delegation (though that's not an issue here).- You could also use
e.target.valuehere—since the change event originates directly from the<select>,targetandcurrentTargetwill point to the same element. Either option works, butcurrentTargetis more explicit if you want to make it clear you're referencing the element the listener is bound to.
Optimize the this binding
Since you're using React.createClass (the older component syntax), you don't need to call .bind(this) in the onChange prop. React.createClass automatically binds all component methods to the component instance. You can simplify that line to:
<select onChange={this.onSelect}>
This avoids creating a new function on every render, which is a small but nice performance win.
Add initial state for a controlled component (recommended!)
To make this a proper controlled component (where the UI always matches the state), add an initial state value and bind the dropdown's value prop to it:
var Dummy = React.createClass({ getInitialState: function() { return { selectedItem: "1" }; // Set your default selected value here }, onSelect: function(e) { this.setState({ selectedItem: e.currentTarget.value }) }, render: function() { return ( <select onChange={this.onSelect} value={this.state.selectedItem}> <option value="1">Item 1</option> <option value="2">Item 2</option> <option value="3">Item 3</option> </select> ) } });
This ensures the dropdown always reflects the current state value, which is the standard pattern for handling form elements in React.
内容的提问来源于stack exchange,提问作者blankface

