首页 > 解决方案 > 已解决:Textfield onChange 不适用于 react 和 MobX

问题描述

我有一个由 MobX 商店控制的文本字段,但是如果我在文本字段中输入一些内容,只有字母才会改变。这是我的代码。有我的错误吗?

我将组件设置为观察者,并且我的 Store 在构造函数中是 makeAutoObservable 。

class SettingsStore {
  constructor() {
    makeAutoObservable(this)

    makePersistable(this, {
      name: 'SampleStore',
      properties: ['roadmapDescription'],
      storage: window.localStorage
    })
  }

  async onChangeRoadmapTitle(name: string): Promise<void> {
    setTimeout(() => {
      console.log('input', name)
      this.roadmapDescription.title = name
      console.log(
        'this.roadmapDescription.title',
        this.roadmapDescription.title
      )
    }, 50)
  }
}

这是我的反应代码

const SettingsGeneral: React.FC<ISettingsGeneral> = observer(({ onSubmit }) => {
  return (
    <div>
      <Form<{ title: string; description: string; dataSource: string }>
        onSubmit={(data) => onSubmit(data)}
      >
        {({ formProps = 'test', submitting }) => (
          <form {...formProps}>
            <FormSection>
              <Field
                aria-required={true}
                name='title'
                label='Name of the Roadmap'
                isRequired
              >
                {({ fieldProps }) => (
                  <Fragment>
                    <TextField
                      testId='roadmap-title-text-field'
                      autoComplete='off'
                      {...fieldProps}
                      className='w-48'
                      onChange={async (
                        e: React.ChangeEvent<HTMLInputElement>
                      ) =>
                        await settingsStore.onChangeRoadmapTitle(e.target.value)
                      }
                      value={settingsStore.roadmapDescription.title}
                    />
                  </Fragment>
                )}
              </Field>
          </form>
        )}
      </Form>
    </div>
  )
})

标签: reactjstypescriptmobxmobx-react

解决方案


我找到了解决方案。错误是我使用 value 而不是 defaultVaule

正确的解决方案是:

<Fragment>
  <TextField
    testId='roadmap-title-text-field'
    autoComplete='off'
    {...fieldProps}
    className='w-48'
    onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
      settingsStore.onChangeRoadmapTitle(e.target.value)
    }
    defaultValue={settingsStore.roadmapDescription.title}
  />
</Fragment>


推荐阅读