简体   繁体   English

以反应最终形式更改嵌套字段的值

[英]Changing the value of nested field in react final form

we are using React Final Form library, and want to change the value of nested field on user's selection.我们正在使用 React Final Form 库,并希望更改用户选择的嵌套字段的值。

It is basically Address form, where on selection of Suburb , I want to change postcode and state .它基本上是地址形式,在选择Suburb ,我想更改postcodestate address is again a nested object in form. address 又是一个嵌套的表单对象。 My Dataset look like :-我的数据集看起来像:-

{
  name: 'xyzx',
  address: {
    suburb: 'xx',
  },
}

I am passing following mutator我正在通过以下 mutator

export const changeValueMutator: Mutator = ([name]: string[], state: MutableState, { changeValue }: Tools) => {
  console.log(state, name);
  changeValue(state, name, value => (value));
};

and calling it as并将其称为

this.props.changeValue('address.suburb', item.suburb);

Nested fields in final-form are referenced with dot notation. final-form嵌套字段用点表示法引用。

https://github.com/final-form/final-form#field-names https://github.com/final-form/final-form#field-names

<Field
    name="address.suburb"
    component="input"
    type="text"
    placeholder="Suburb"
/>

I found the answer from one of the test case in library我从库中的一个测试用例中找到了答案

I corrected it by changing my mutator method as below (take newValue as second arg in first parameter array).我通过如下更改我的 mutator 方法来纠正它(将 newValue 作为第一个参数数组中的第二个 arg)。 https://github.com/final-form/react-final-form/blob/379755c24570bf0e1cedaa2f6783e642d2e2b369/src/ReactFinalForm.d.test.tsx#L69 https://github.com/final-form/react-final-form/blob/379755c24570bf0e1cedaa2f6783e642d2e2b369/src/ReactFinalForm.d.test.tsx#L69

export const changeValueMutator: Mutator =
  ([name, newValue]: string[], state: MutableState, { changeValue }: Tools) => {
  console.log(state, name);
  changeValue(state, name, value => (newValue));
};

You can try this, if你可以试试这个,如果

state = {
  json : {
    name: 'xyzx',
    address: {
    suburb: 'xx',
  },
}

this.state.json.address.suburb = "yy";
this.setState({json : this.state.json});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM