How to set/change Field value from external user action

血红的双手。 提交于 2019-12-03 11:01:26

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>
    </>
  )}
/>

The accepted answer is great and led me to my solution, but in case anyone comes here like I did looking for a way to modify field values from outside of the React application, you can do it by making a completely generic mutator that sets any field to any value, and getting a global reference to the bound mutator in the form like so

<Form
  mutators={{
    // expect (field, value) args from the mutator
    setValue: ([field, value], state, { changeValue }) => {
      changeValue(state, field, () => value)
    }
  }}
  render={({ mutators, ...rest }) => {
    // put the reference on a window variable of your choice here
    if (!window.setFormValue) window.setFormValue = mutators.setValue

    return (
      <>
        <Field name="field1">...</Field>
        <Field name="field2">...</Field>
        ...
      </>
    )
  }}
/>

// somewhere else, outside of the React application

window.setFormValue('field1', 'value1')
window.setFormValue('field2', 'value2')

Disclaimer: The above pattern shouldn't be used unless absolutely necessary, for very particular usecases. For example, I'm using it for automating filling of fields from code which must be external to my React app. You shouldn't do this for actual application code. But if you do need to do it, it works great!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!