根本問題是.value
對於具有multiple
屬性的select元素僅返回其包含的第一個選定選項元素的值。因此,當ValueLink mixin調用event.target.value
以獲取select
的新值時,它不返回所需的數組以使value
屬性有效。
你可以圍繞select
建立一個小包裝來完成這項工作;這裏是我的版本(plus a JSFiddle example):
// A select element that supports `multiple` and `valueLink` correctly
var BetterSelect = React.createClass({
render: function() {
if (this.props.valueLink) {
return this.transferPropsTo(
<select value={this.props.valueLink.value}
valueLink={null} onChange={this.handleChange}>
{this.props.children}
</select>
);
} else {
return this.transferPropsTo(
<select onChange={this.handleChange}>
{this.props.children}
</select>
);
}
},
handleChange: function(e) {
var selectedValue;
if (this.props.multiple) {
// We have to iterate the `options` elements
// to figure out which ones are selected.
selectedValue = [];
var options = e.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = e.target.value;
}
// Fire onChange manually if it exists since we overwrote it
this.props.onChange && this.props.onChange(e);
// Finally, manually take care of any valueLink passed
if (this.props.valueLink) {
this.props.valueLink.requestChange(selectedValue);
}
}
});
// Let's try it out:
var Application = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return { value: ['Apples', 'Oranges'] };
},
render: function() {
return (
<div>
<pre>{JSON.stringify(this.state.value)}</pre>
<BetterSelect multiple valueLink={this.linkState('value')}>
<option value='Apples'>Apples</option>
<option value='Bananas'>Bananas</option>
<option value='Oranges'>Oranges</option>
</BetterSelect>
</div>
);
}
});
我不明白,爲什麼選擇「值」屬性接受一個數組作爲二傳手當多個= TRUE;但僅當用作吸氣劑時才返回第一個值;這感覺很奇怪。 –
您正在設置反應組件的值,但是來自DOM事件'event.target'是實際的DOM節點。 –
我已經打開了一個問題,使用'ReactLink',順便說一句:https://github.com/facebook/react/pull/1761 –