我正在创建一个 react 应用程序,我想在每次单击按钮时渲染一个组件。但我只能做一次。
class AddForm extends React.Component{
constructor(props){
super(props);
this.state={
anotherForm:false,
}
this.newForm=this.newForm.bind(this);
}
newForm(){
this.setState({
anotherForm:true
})
}
render(){
return(
<div>
<button onClick={this.newForm}>AddForm</button>
<EducationDetails/>
{this.state.anotherForm?<EducationDetails/>:null}
</div>
)
}
}
这里,只要单击 AddForm 按钮,就会呈现组件 EducationDetails
。但我无法弄清楚。
最佳答案
这是一个工作 jsfiddle
我们假设这是您的教育详细信息组件。
class EducationDetails extends React.Component {
constructor(props) {
super(props);
}
render() {
return (<div>
<p>FirstName: <input type="text" value={this.props.value || ''} /></p>
<p>LastName: <input type="text" value={this.props.value || ''} /></p>
</div>
);
}
}
在您的 AddForm 组件中,您可以进行计数,每当您单击“添加更多”按钮时,就会增加您的计数并根据您的计数状态显示教育详细信息表单。
class AddForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: [], count: 1}; //initial you'll have one form
}
addMore(){
this.setState({count: this.state.count+1})//on click add more forms
}
displayForm(){
let forms = [];
for(let i = 0; i < this.state.count; i++){
forms.push(
<div key={i}>
<EducationDetails value={this.state.value[i] || ''} />
</div>
)
}
return forms || null;
}
render() {
return (
<form >
{this.displayForm()}
<input type='button' value='add more' onClick={this.addMore.bind(this)}/>
</form>
);
}
}
ReactDOM.render(<AddForm />, document.getElementById('container'));
您还可以使用相同的概念减少您的计数来删除表单,例如
removeClick(){
this.setState({count: this.state.count - 1})
}
在“添加更多”按钮下方,添加另一个用于删除的按钮
<input type='button' value='remove' onClick={this.removeClick.bind(this)}/>
关于reactjs - 如何在每次单击按钮时渲染 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45779386/