答案 0 :(得分:1)
我相信这就是你要找的东西
class App extends React.Component {
constructor (props) {
super(props);
// I am storing the inputs definition here, but
// it could be something that you retrieve from
// your redux store or an API call
this.state = {
inputs : [{
name : 'vowels',
value : 'a',
options : ['a','b','c']
}, {
name : 'numbers',
value : 1,
options : [1,2,3]
}]
}
}
// createSelect creates the select input based
// on the input definition in the state
createSelect (inputOptions) {
const {options} = inputOptions;
// Create options for the select
const opts = options.map((o) => {
return (<option value={o}>{o}</option>)
});
// Choosing the value
// if the state does not have a key with the name
// of the select yet, then use the value of the input definition
// when the select change its value this.state[inputOptions.name]
// will be used
const val = this.state[inputOptions.name] || inputOptions.value
return (
<select value={val} onChange={this.createChangeHandler(inputOptions.name)}>
{opts}
</select>
)
}
// createChangeHandler is a curried function that
// allows to specify which state value will be set
createChangeHandler (field) {
return (e) => {
this.setState({
[field] : e.target.value
})
}
}
renderSelects () {
const {inputs} = this.state;
return inputs.map((input) => {
return this.createSelect(input)
});
}
render () {
return (
<form>
{this.renderSelects()}
</form>
);
}
}
ReactDOM.render(
<App/>,
document.querySelector('#root')
)
并且有一个demo