问题
I have a ReactJS
component:
var RegionsList = React.createClass({
handleChange: function () {
var regionId = this.refs.userRegions.getDOMNode().value;
this.props.onRegionSelected(regionId);
},
componentDidMount: function() {
$.get("/translation/activeuserregions", function(result) {
if(this.isMounted()) {
this.setState({
selectedRegionId: result.SelectedRegionId,
regions: result.Regions
})
}
}.bind(this));
},
getInitialState: function(props) {
return {
selectedRegionId: '',
regions: []
}
},
render: function() {
return (
<div id="RegionsListForm" className="navbar-form navbar-left regions-list">
<div className="input-group navbar-searchbox">
<span className="input-group-addon">
<span>Region</span>
</span>
<select ref="userRegions" onChange={this.handleChange} defaultValue={this.state.selectedRegionId} className="form-control valid" id="region" name="region" aria-invalid="false">
{this.state.regions.map(function(region) {
return <option key={region.Id} value={region.Id} label={region.RegionName}>{region.RegionName}</option>
})}
</select>
</div>
</div>
);
},
})
It appears to work correctly. But initially it does not render with the correct item selected. Although the defaultValue
appears to be set correctly so I don't understand why.
What am I doing wrong?
回答1:
When the <select>
is initially mounted, the default value is ''
. Once an uncontrolled form component is in the DOM, React doesn't look updates to the defaultValue
prop. In this case it looks like your intention is to always have the selectedRegionId
state match what's shown to the user, so you may want to change defaultValue
to value
and add a this.setState({selectedRegionId: regionId});
call to your onChange handler; then your component state and the DOM will always be in sync.
来源:https://stackoverflow.com/questions/24884294/why-doesnt-this-select-list-render-with-the-correct-item-selected-based-on-the