【问题标题】:solved: Textfield onChange not works with react and MobX已解决:Textfield onChange 不适用于 react 和 MobX
【发布时间】:2021-10-23 15:41:58
【问题描述】:

我有一个由 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>
  )
})

【问题讨论】:

    标签: reactjs typescript mobx mobx-react


    【解决方案1】:

    我找到了解决方案。错误是我使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      相关资源
      最近更新 更多