redux-form:单击更改特定字段值
redux-form: Change specific field value on click
如何更改事件中特定字段的值。
示例 不工作(无法读取未定义的 属性 'firstname')
onclick1() {
this.props.fields.firstname.onChange("John")
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.submit.bind(this))}>
<Field
name="firstname"
component={TextField}
label="first name"
/>
<button onClick="this.onclick1()">Set name to John</button>
<button type="submit">
okay
</button>
</form>
这里提出了这个解决方案,但它对我不起作用
redux-form v7
我发现您的代码存在一些问题:
<button onClick="this.onclick1()">
应该是:
<button onClick={this.onclick1}>
onclick1 应该以某种方式绑定到组件。此外,我通常使用 change
方法来设置字段值。所以我会将您的代码更改为:
class ComplexForm extends React.PureComponent {
constructor(props) {
super(props);
this.onclick1 = this.onclick1.bind(this);
}
onclick1() {
this.props.change("firstname", "John");
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<Field name="firstname" component="input" label="first name" />
<button onClick={this.onclick1}>Set name to John</button>
</form>
);
}
}
请注意,我只重写了您代码的一些相关部分,并且我使用的是标准 input
组件,因为我不知道您的 TextField
是什么样子。查看在线演示 here
如何更改事件中特定字段的值。
示例 不工作(无法读取未定义的 属性 'firstname')
onclick1() {
this.props.fields.firstname.onChange("John")
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.submit.bind(this))}>
<Field
name="firstname"
component={TextField}
label="first name"
/>
<button onClick="this.onclick1()">Set name to John</button>
<button type="submit">
okay
</button>
</form>
这里提出了这个解决方案,但它对我不起作用
redux-form v7
我发现您的代码存在一些问题:
<button onClick="this.onclick1()">
应该是:
<button onClick={this.onclick1}>
onclick1 应该以某种方式绑定到组件。此外,我通常使用 change
方法来设置字段值。所以我会将您的代码更改为:
class ComplexForm extends React.PureComponent {
constructor(props) {
super(props);
this.onclick1 = this.onclick1.bind(this);
}
onclick1() {
this.props.change("firstname", "John");
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<Field name="firstname" component="input" label="first name" />
<button onClick={this.onclick1}>Set name to John</button>
</form>
);
}
}
请注意,我只重写了您代码的一些相关部分,并且我使用的是标准 input
组件,因为我不知道您的 TextField
是什么样子。查看在线演示 here