簡體   English   中英

以多步形式反應手柄狀態

[英]React handle state in multi-step form

我正在嘗試在React上創建一個多步驟表單。

現在,我有了一個步驟的表單,該表單將僅呈現該組件並在提交表單后顯示另一個組件。

這可以在本要點上找到(對於縮進表示歉意,Github總是將其擰緊)。

如果我想讓父組件Form.js像這樣渲染每個表單步驟,該如何處理多表單表單的狀態?

Form.js -> Step1 (Child of Form) -> Step2 (Child of Step1) -> etc?

我嘗試了各種NPM模塊,但它們似乎相處或工作正常。

有沒有一種方法可以獲取父表單組件中所有步驟的狀態,以便可以從那里提交數據(並且還可以驗證每個步驟並在成功提交表單后重置狀態)?

這是當前的一步狀態代碼

constructor(props) {
  super(props);

  this.state = {
   phone: "",
   firstname: "",
   lastname: "",
   disabled: false,
   successIsVisible: false
  }

    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(name, value){
  let state = this.state;
  state[name] = value;
  this.setState({state});
}

輸入示例

<input id="lastname" className="form-control" placeholder="Your last name" onChange={this.handleChange.bind(this, 'lastname')} name="lastname" value={this.state.lastname} />

您可以使用回調將子級state設置為父級組件:

class Parent extends React.Component{
    constructor(){
        super();
        this.state = {
            childsState: null
        }
        this.getChildState = this.getChildState.bind(this);
    }
    getChildState(childrenName, childrenState){
        this.setState({childrenName: childrenState}); //with click Save button in FirstChildren you will get state of this component
    }
    render(){
        return(
            <FirstChildren getChildState={this.getChildState}/>
        )
    }
}

class FirstChildren extends React.Component{
    constructor(){
        super();
        this.state = {
            data: null
        }
        this.saveData = this.saveData.bind(this);
    }
    saveData(e){
        this.setState({data: e.target.value})
    }
    render(){
        return(
            <div>
                <input type="text" onBlur={() => this.saveData(e)} />
                <button onClick={() => this.props.getChildState("firstChildsState", this.state)}> Save </button>
            </div>
        );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM