reactjs - 已解决: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>
)
})
解决方案
我找到了解决方案。错误是我使用 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>
推荐阅读
- reactjs - React 响应式模态 - animationDuration
- python - Python:如何在 while 循环中跟踪两个或多个相等的变量
- sql - 2 个选择语句,1 个变量
- docusignapi - Docusign PowerForm - 不带 URL 参数的自动填充
- php - 使用 Laravel 在标头的 x-frame-options 中添加多个域
- scala - 有没有办法将维加斯(用于 Vega-lite 的 scala DSL)直接渲染为 png?
- r - R - 在使用 ChemoSpec 包之前从不同数据集中的重复数据计算平均值
- xamarin.forms - Azure 表存储 - 如何在更新或合并后保持列的初始顺序?
- wcf - 带有 SSL 证书的 Net.TCP 是否可以在 Internet 上使用
- jquery - 根据光标所在的位置向 div 添加类