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