1
我有一個FIELDS對象,其中包含許多字段(也是對象)的設置,這些字段將用於使用函數renderField在頁面中構建輸入字段。其中一些字段需要編輯組件狀態的功能。我需要這個能夠在用戶填寫表單時做某種自動完成。將函數從對象傳遞到組件以編輯狀態
代碼如下所示。
import React from 'react';
import {Field,reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import _ from 'lodash';
// objects that will be used to create the form
const FIELDS = {
first_name: {
type: 'text',
label: 'First name',
onChange: function(e){
this.setstate({first_name:e.target.value})
},
last_name: {
type: 'text',
label: 'last name',
onChange: function(e){
this.setstate({last_name:e.target.value})
},
...
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
first_name : '',
last_name : '',
birth : '',
sex:''
};
}
renderField(field) {
const fieldConfig = FIELDS[field.input.name];
const {meta: {touched, error}} = field;
return (
<div className={`form-group ${touched && error ? 'has-danger' :''}`}>
<br />
<label>{fieldConfig.label}</label>
<input
{...fieldConfig}
{...field.input}
/>
<div className='text-help'>{touched ? error : ""}</div>
<br />
</div>
);
}
onSubmit(){
...
}
render() {
const {handleSubmit} = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
{ _.keys(FIELDS).map(key => {
return <Field name={key} key={key} component={this.renderField} />;
})
}
<button type='submit'>Submit</button>
</form>
</div>
)
}
}
export default reduxForm({
// validate,
form: 'Form example'
})(
connect(null)(App)
);
我知道,我不能叫this.setState()這個方法,但我不知道我能怎麼綁定功能的組件內部的對象內。我做了大量的研究,似乎無法找到解決方案。我不知道是不是因爲我沒有遵循好的做法。
在此先感謝
根據您的導入來判斷,您正在嘗試在此項目中使用Redux。如果是這樣,你需要使用動作和縮減器來設置你的Redux狀態,而不是'setState()'和本地狀態(一般情況下)。如果您尚未閱讀,請閱讀:http://redux.js.org/docs/introduction/ – IronWaffleMan
感謝您的回覆。是的,我將在我的項目中使用redux,但我不確定是否將這些值置於應用程序狀態是好的,因爲這些值只會在此組件中使用。我需要這些值來自動填寫表單中的一個字段,因此用戶只需填寫該字段的一小部分。即使我使用了redux,我也不確定如何通過將this.props.actionName放入對象「first_name」和「last_name」中來訪問這些動作。 –
我不明白內部組件狀態應該如何幫助自動完成。該內部狀態將存儲Redux窗體已爲您存儲的完全相同的值。如果已知某些字段的值,則可以使用此處顯示的技術從Redux狀態初始化表單字段https://redux-form.com/7.0.4/examples/initializefromstate/ – jonahe