【发布时间】:2017-04-12 15:08:35
【问题描述】:
我有一个很长的反应形式。之前,它有一堆这样定义的组件:
<input
type='text'
value={this.state.form.nameOfFormField}
onChange={this.updateForm('nameOfFormField')} />
其中updateForm是(field) => (e) => {}形式的函数,方便代码复用。
我想让它更易于维护,所以我创建了一个组件,SpecialInput,它的定义如下:
const SpecialInputBuilder = (form, onChange) => ({ field, ..props }) => (
<input
type='text'
value={form[field]}
onChange={onChange(field)}
{...props} />
)
现在,我可以像这样在渲染期间定义输入:
const SpecialInput = SpecialInputBuilder(this.state.form, this.updateForm)
并像这样在组件中使用它:
<SpecialInput field='nameOfFormField' />
显然,这要简洁得多。但这也意味着每次输入输入字段时(即调用updateForm 时)输入字段都会失去焦点,因为每次调用render 函数时都会定义SpecialInput。为每个元素定义一个key 似乎并不能缓解这个问题。如何在仍然使用这个更简单的组件的同时解决这个问题?有没有中间地带?
【问题讨论】:
-
我能想到的唯一方法是将输入定义为反应类上的项目。也就是在 componentWillMount 你可以创建一个
this.specialInput = SpecialInputBuilder(this.state.form, this.updateForm)然后在你的渲染中使用已经定义的输入。
标签: javascript reactjs