1
因此,我有一堆用戶可以來回導航的表單,但是當他回來時,表單應該是他們離開它的時候,並且所有的值都可以立即提交。保存離開頁面後的表格中的值reactjs
我想保留一個大對象,它臨時存儲所有表單的值,並且是在它結束時提交的。 每當我回到頁面時,我只是將該特定對象放在value屬性中。
問題在於,一旦我回到填好的表格,我無法再編輯它。
我該怎麼做才能做到這一點?另外,如果有更好的方法來完成這個工作,我願意完全改變它。
下面是一些相關的代碼有一些意見解釋的事情:
// form3 only has to text fields, and form4 only has a file entry,
//which is why they aren't objects
//form1 and form2 on the other hand are huge and generate dynamically (I get
//all their fields through a get request and don't necessarily know
//how many there will be
export var formDataObject = {
form1:{},
form2:{},
form3:{
field1:"",
field2:""
},
form4:""
};
// for the next part I'll use form3 as an example since it is simple:
//The Form3 component is just a simple text input, I include the code
//of that too in case it's needed
export default class FullForm3 extends Component{
constructor(props){
super(props);
this.state ={
initial_field1: formDataObject.form3.field1,
initial_field2: formDataObject.form3.field2
}
}
render(){
var field1Value, field2Value;
if (this.state.initial_field1.length>0)
field1Value = formDataObject.form3.field1;
if (this.state.initial_field2.length>0)
field2Value = formDataObject.form3.field2;
return (
<div>
<Panel>
<Form3 controlId="field1Id" label={field1Label}
value={field1Value}/>
<br/><br/>
<Form3 controlId="field2Id" label={field2Label}
value={field2Value}/>
</div>
);
}
}
class Form3 extends Component{
constructor(props){
super(props);
this.state = {
value: formDataObject.form3,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
const value = Object.assign({}, this.state.value);
value[e.target.id] = e.target.value;
this.setState({ value });
formDataObject.form3= this.state.value;
}
handleSubmit(e){
//things for submit (not important)
}
render(){
return (
<Form inline onSubmit={this.handleSubmit}>
<ControlLabel>{this.props.label}</ControlLabel>
<FormControl
type='text' label='Text'
value={this.props.value} onChange={this.handleChange}
/>
</FormGroup>
</Form>
)
}
}
我覺得你的問題是,你正在做的React中的一些內容,以及React中沒有的東西(全局對象)。嘗試將你的組件分成多個文件,並且只通過道具傳遞數據給他們。你需要的是一個父組件,該組件首先保存所有表單的狀態(類似於你的全局對象),並且有一個onchange處理器,它傳遞給表單以改變它自己的狀態。我建議看看:https://facebook.github.io/react/docs/lifting-state-up.html –
@MatthewHerbst閱讀教程並重新創建它。完美工作!非常感謝! – theJuls