reactjs - 如何在每次单击按钮时渲染 react 组件?

标签 reactjs

我正在创建一个 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/

相关文章:

javascript - 错误模块构建失败 : SyntaxError: Unexpected token

javascript - 如何在 JavaScript 中实现步进决策流程?

node.js - 如何使用 MongoDB + NodeJS Express 向 ReactJS React Router 和 Redux 添加登录身份验证和 session ?

javascript - 不断收到 TypeError : guide. map is not a function

javascript - react Redux : dispatch returning data to component

Javascript ESLint 错误 - 在条件表达式中不必要地使用 bool 文字

node.js - 如何从 Influxdb 的 NodeJS API 获取 ReactJS 中的数据?

try-catch - 你能用 try/catch block 捕获 React.js 应用程序的所有错误吗?

javascript - 改变对象的数组

reactjs - redux props 更改时不会调用 componentWillReceiveProps