我想从数组中为select表单生成选项。这是在React组件的渲染方法中,并使用JSX进行转换。
render: function(){
return(
<div className="control-group">
<select id="select-food" placeholder="Pick a food...">
<option value="">select a food</option>
{Object.keys(this.state.foods).forEach((food) => {
return (<option value={food}>{food}</option>);
})}
</select>
</div>
);
}
我可以使用forEach
将console.log()
循环中的食物输出到控制台就好了,但HTML还没有生成。我在这里错过了什么才能让它发挥作用?
答案 0 :(得分:6)
您无法从forEach
循环内返回。您将要使用.map()
代替,这将返回一个新数组。有关map
here。
render: function() {
return (
<div className="control-group">
<select id="select-food" placeholder="Pick a food...">
<option value="">select a food</option>
{Object.keys(this.state.foods).map((food) => {
return (<option value={food}>{food}</option>);
})}
</select>
</div>
);
}
答案 1 :(得分:-1)
使用map或helper函数检查链接https://egghead.io/lessons/react-dynamically-generated-components。开始的好地方
render: function(){
let options = ['book', 'cat', 'dog'];
return(
<div className="control-group">
<select id="select-food" placeholder="Pick a food...">
{options.map(food => <option key={id} value={food}>{food}</option>)}
</select>
</div>
);
}
&#13;
我的演示中的另一个解决方案
renderRepository() {
let repository = this.props.repositories.find((repo)=>repo.name === this.props.params.
repo_name);
let stars = [];
for (var i = 0; i < repository.stargazers_count; i++) {
stars.push('');
}
return(
<div>
<h2>{repository.name}</h2>
<p>{repository.description}</p>
<span>{stars}</span>
</div>
);
}
render() {
if(this.props.repositories.length > 0 ){
return this.renderRepository();
} else {
return <h4>Loading...</h4>;
}
}
}
&#13;