简体   繁体   English

在一个组件中加载不同的组件-reactjs

[英]Loading different components in one component - reactjs

I am creating a 4 steps form in reactjs. 我在reactjs中创建一个4个步骤的表单。

Main components is loading sub-components inside it. 主要组件是在其中加载子组件。

When user fill one form and press continue, it should save values of form 1 and load form2 in place of form one. 当用户填写一张表格并按继续键时,它应保存表格1的值并加载表格2代替表格1。 How would i achieve it. 我将如何实现它。

Form 1 表格1

handleClick() { //When user submits form 1
    //Save All Values of form 1 and load form 2 


    //window.openAppRoute("/payments"); //Not Working
    //hashHistory.push('/dashboard'); //Not Working
    //history.push('/dashboard'); //Not Working
}

Main component: 主要组成部分:

return (
  <div className="custom-container">

    <div className="page-content">
        <Form1 />
        //<Form2 /> Should load next
        //<Form3 /> Should load next
    </div>
  </div>
)

One solution is to keep form data on the main component and handle changes with event handlers 一种解决方案是将表单数据保留在主要组件上,并使用事件处理程序处理更改

Given your example: 给出您的示例:

const { data, step } = this.props

return (
  <div>
    {step === 0 && <Form1 data={data} onChange={/**/} />}
    {step === 1 && <Form2 data={data} onChange={/**/} />}
    {step === 2 && <Form3 data={data} onChange={/**/} />}
  </div>
)

Whenever a change is triggered, you have control over data to make the appropriate changes and later dispatch them to your redux store, state, backend api... 每当触发更改时,您就可以控制data以进行适当的更改,然后将它们分派到您的redux存储,状态,后端api ...

There are two ways you could do this. 您可以通过两种方式执行此操作。 Either create each component inside your container App component and have a state variable control which step should be shown, or create sub-routes that link to each other. 在您的容器App组件内创建每个组件,并使用状态变量控制应显示哪个步骤,或者创建相互链接的子路由。

Example of first approach: 第一种方法的示例:

 class MyApp extends React.Component { constructor() { super(); this.state = { step: 0 }; } nextStep = () => { this.setState((prevState) => ({step: prevState.step + 1})); } render() { let {step} = this.state; let form = [<Form1 />, <Form2 />, <Form3 />]; return( <div> {form[step]} {form.length-1 > step && <button onClick={this.nextStep}>Next</button>} </div> ); } } const Form1 = () => <div>Form 1</div>; const Form2 = () => <div>Form 2</div>; const Form3 = () => <div>Form 3</div>; ReactDOM.render(<MyApp />, document.getElementById("app")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM