问题
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>
</>
)}
/>
回答2:
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!
来源:https://stackoverflow.com/questions/48901016/how-to-set-change-field-value-from-external-user-action-react-final-form