gpt4 book ai didi

javascript - 如何在 React JS - JSX 中动态创建输入文本字段?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:12 24 4
gpt4 key购买 nike

我是 reactjs 的新手,我遇到了一个场景,我必须创建 6 个彼此非常相似的输入字段。现在我在类的渲染方法中有这样的东西,

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>
);
}

代码丑陋且冗余,无论如何我可以动态地做到这一点吗?

最佳答案

如何定义一个像这样的 Answer 组件(只显示 render 方法):

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>
);
}

然后在您的父组件上,您只需导入它并像这样使用它:

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 的建议,这里是一个使用 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>
);
}

关于javascript - 如何在 React JS - JSX 中动态创建输入文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com