How to set/change Field value from external user a

2019-04-22 11:39发布

问题:

There are many situations in which we might want to set the value of a specific field within a form to help out the user.

For example, an online fruit store may ask users how many apples they want to buy. To help users out, we could have 3 buttons such as

  • "minimum" - sets field value to the minimum quantity the store can feasibly sell
  • "maximum" - ditto, but for max
  • "what I bought last time" - sets field value to the quantity of apples the user bought the last time

After going over what I thought were the two most relevant examples (Loading and Initializing Values and Calculated Fields), I still can't figure this one out without getting too hacky.

How can we set a field's value from a user's action (such as clicking a button)?

回答1:

Erik has a wonderful post on mutators, which inspired me to find the solution I was looking for:

<Form
  mutators={{
    setMin: (args, state, utils) => {
      utils.changeValue(state, 'apples', () => 1)
    },
    setMax: (args, state, utils) => {
      utils.changeValue(state, 'apples', () => 100)
    },
    setLast: (args, state, utils) => {
      utils.changeValue(state, 'apples', () => 6)
    },
  }}

  render={({ mutators, ...rest }) => (
    <>
      <button onClick={mutators.setMin}>minimum apples</button>
      <button onClick={mutators.setMax}>maximum apples</button>
      <button onClick={mutators.setLast}>what I bought last time</button>
    </>
  )}
/>