How to set/change Field value from external user action

前端 未结 2 499
忘掉有多难
忘掉有多难 2020-12-30 22:21

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

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 22:58

    This can be accomplished by providing a mutators object to the Form component containing the necessary mutators, which will be made available to your component:

    { utils.changeValue(state, 'apples', () => 1) }, setMax: (args, state, utils) => { utils.changeValue(state, 'apples', () => 100) }, setLast: (args, state, utils) => { utils.changeValue(state, 'apples', () => 6) }, }} render={({ form, ...rest }) => ( <> )} />

    If you need to interact with the form from outside the React app (eg, you're using micro front-ends) you can save the form object (or any methods within) to the global scope using the render method, and call them as needed:

    render={({ form, ...rest }) => {
      window.myGlobalProp = window.myGlobalProp ?? form;
    
      // ... rest of code
    )}
    
    // later anywhere else in app
    myGlobalProp.form.mutators.setMax
    

    Erik's post

提交回复
热议问题