本文介绍了如何在反应js-JSX中动态创建输入文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对reactjs很新,我遇到了一个场景,我要创建6个非常相似的输入字段。现在我在类的渲染方法中有这样的东西,
I'm pretty new to reactjs, i came across a scenario where i've to create 6 input fields which are very much similar to each other. Right now i've something like this in my render method of class,
render () {
return (
<div>
<p>
<label htmlFor="answer1">Answer:</label><br/>
<input
type="text"
name="answer1"
id="answer1"
className="answer"
value={this.state.answer1}
onChange={this._handleChange}
/>
</p>
<p>
<input
type="text"
name="answer2"
id="answer2"
className="answer"
value={this.state.answer2}
onChange={this._handleChange}
/>
</p>
<p>
<input
type="text"
name="answer3"
id="answer3"
className="answer"
value={this.state.answer3}
onChange={this._handleChange}
/>
</p>
<p>
<input
type="text"
name="answer4"
id="answer4"
className="answer"
value={this.state.answer4}
onChange={this._handleChange}
/>
</p>
<p>
<input
type="text"
name="answer5"
id="answer5"
className="answer"
value={this.state.answer5}
onChange={this._handleChange}
/>
</p>
<p>
<input
type="text"
name="answer6"
id="answer6"
className="answer"
value={this.state.answer6}
onChange={this._handleChange}
/>
</p>
</div>
);
}
代码是丑陋和多余的,无论如何我可以动态地执行此操作吗?
The code is ugly and redundant, is there anyway i could do this dynamically?
推荐答案
如何定义这样的答案
组件(仅显示渲染方法):
How about defining an Answer
component like this (only showing the render method):
render() {
return (
<p>
<label htmlFor={this.props.name}>Answer:</label>
<input
type="text"
name={this.props.name}
className="answer"
value={this.props.value}
onChange={this.props.handleChange}
/>
</p>
);
}
然后在您的父组件上导入它并使用它: / p>
And then on your parent component you just import it and use it like:
var Answer = require('./answer.js');
//..
render() {
return (
<div>
<Answer name="answer1" value={this.state.answer1} handleChange={this._handleChange} />
<Answer name="answer2" value={this.state.answer2} handleChange={this._handleChange} />
<Answer name="answer3" value={this.state.answer3} handleChange={this._handleChange} />
// add all your Answer components
</div>
);
}
在Thylossus建议之后,这是一个使用地图的示例
:
Following Thylossus suggestion, here is an example using map
:
var Answer = require('./answer.js');
//...
render() {
// this is supposing you've got an answers array of { name: ..., value: ...} object
var answers = this.state.answers.map(function(a) {
return(<Answer name={a.name} value={a.value} handleChange={this._handleChange} />)
});
return (
<div>
{ answers }
</div>
);
}
这篇关于如何在反应js-JSX中动态创建输入文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!