0
我想自動將value='foo'
屬性插入選項元素,以便在元素重新呈現時可以輕鬆地從保存的狀態中選擇選項。如何在使用React進行渲染時獲取子元素值?
目前我可以手動添加價值,它的工作原理,但我試圖在呈現這樣的孩子時自動化。但是我找不到價值。有任何想法嗎?
// form.jsx
<Select
label='Select a thing'
name='things'
updateForm={update}
formState={fstate}>
<option>Foo</option>
<option>Bar</option>
<option>Baz</option>
</Select>
// Select.jsx
Select = React.createClass({
// pass this.name down to this.props.children manually
renderChildren: function() {
return React.Children.map(this.props.children, function (child) {
debugger
// can't find "foo", "bar" here
return React.addons.cloneWithProps(child, {
name: this.props.name,
value: (get child value)
});
}.bind(this));
},
handleChange(e) {
var value = e.currentTarget.value;
// save to db and save to formState
this.props.updateForm(this.props.name, value);
},
render() {
return (
<div>
<label>{ this.props.label }</label>
<select
onChange={this.handleChange}
defaultValue={ this.props.formState[this.props.name] }>
{ this.renderChildren() }
</select>
</div>
);
}
});
// render this HTML
<div>
<label>Select a thing</label>
<select class="form-control" >
<option name="thing" value="foo">foo</option>
<option name="thing" value="bar">bar</option>
<option name="thing" value="baz">baz</option>
</select>
</div>
啊,太簡單了!感謝Davide! – SkinnyG33k