【问题标题】:redux-form: Change specific field value on clickredux-form:单击时更改特定字段值
【发布时间】:2017-12-27 09:29:46
【问题描述】:

如何更改事件中特定字段的值。

示例不起作用(无法读取未定义的属性“名字”)

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>

这里提出了这个解决方案,但它对我不起作用 https://stackoverflow.com/a/36916183/160059

redux-form v7

【问题讨论】:

  • 您的表单看起来如何?你会分享一些代码吗?
  • @Dario 更新示例

标签: reactjs redux redux-form


【解决方案1】:

我发现您的代码中存在一些问题:

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2017-12-27
    • 2018-05-03
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多