我有以下类(class):
class App extends Component {
constructor(props){
super(props);
this.state = {value: 'currentlyReading'};
this.handleChange = this.handleChange.bind(this);
}
bookOptions = [{
value: 'currentlyReading',
text: 'Currently Reading'
},
{
value: 'wantToRead',
text: 'Want to Read'
},
{
value: 'read',
text: 'Read'
},
{
value: 'none',
text: 'None'
}]
onHandleChange = (e) => {
this.setState({
state: e.target.value
})
};
handleChange(e){
this.setState({value: e.target.value});
}
render() {
return (
<select value={this.state.value} onChange={this.handleChange}>
{
this.bookOptions.map((c) => {
<option value={c.value} >{c.text}</option>
})
}
</select>
);
}
}
如果我使用常规 html 语法渲染选择列表,那么它可以完美工作,就好像我尝试动态创建它一样,它不会加载任何内容。您将如何在 React 中动态创建一个列表,以便它保持其绑定(bind)?
如有任何建议,我们将不胜感激!
谢谢。
最佳答案
当您在以下代码中使用花括号时:
this.bookOptions.map((c) => {
<option value={c.value} >{c.text}</option>
})
您没有返回任何内容,因此您正在渲染一个未定义元素的数组。删除它,您的代码应该按预期工作。请参阅下面的工作代码。
class App extends React.Component {
constructor(props){
super(props);
this.state = {value: 'currentlyReading'};
this.handleChange = this.handleChange.bind(this);
}
bookOptions = [{
value: 'currentlyReading',
text: 'Currently Reading'
},
{
value: 'wantToRead',
text: 'Want to Read'
},
{
value: 'read',
text: 'Read'
},
{
value: 'none',
text: 'None'
}]
onHandleChange = (e) => {
this.setState({
state: e.target.value
})
};
handleChange(e){
this.setState({value: e.target.value});
}
render() {
return (
<select value={this.state.value} onChange={this.handleChange}>
{
this.bookOptions.map((c) => <option key={c.text} value={c.value} >{c.text}</option>)
}
</select>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
关于javascript - 在 react 中将数据从数组加载到选择列表中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982286/