javascript - 如何编写通用方法来处理 React 中的多个状态更改
问题描述
我正在用 React 构建一个运动跟踪器应用程序。
现在,我正在构建 CreateExercise 组件来提交表单,因此我需要更新每个值的状态。为此,我创建了处理这些更改的方法(onChangeUsername、onChangeDescription、onChangeDuration 等...),但我不太喜欢重复这样的方法。
如何编写更通用的方法来处理此任务?
class CreateExercise extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
description: '',
duration: 0,
date: new Date(),
users: []
}
}
onChangeUsername = (e) => {
this.setState({
username: e.target.value
});
}
onChangeDescription = (e) => {
this.setState({
description: e.target.value
});
}
onChangeDuration = (e) => {
this.setState({
duration: e.target.value
});
}
onChangeDate = (date) => {
this.setState({
date: date
});
}
onSubmit = (e) => {
e.preventDefault();
const exercise = {
username: this.state.username,
description: this.state.description,
duration: this.state.duration,
date: this.state.date
}
console.log(exercise);
window.location = '/';
}
render() {
return(
<div>
<h3>Create New Exercise Log</h3>
<form onSubmit={ this.onSubmit }>
<div className='form-group'>
<label>Username:</label>
<select
ref='userInput'
required
className='form-control'
value={ this.state.username }
onChange={ this.onChangeUsername }
>
{ this.state.users.map((user) => (
<option key={user} value={user}>{user}</option>
))
}
</select>
</div>
<div className='form-group'>
<label>Description:</label>
<input
type='text'
required
className='form-control'
value={ this.state.description }
onChange={ this.onChangeDescription}
/>
</div>
<div className='form-group'>
<label>Duration:</label>
<input
type='text'
className='form-control'
value={ this.state.duration }
onChange={ this.onChangeDuration }
/>
</div>
<div className='form-group'>
<label>Date:</label>
<div>
<DatePicker
selected={ this.state.date }
onChange={ this.onChangeDate }
/>
</div>
</div>
<div className='form-groupe'>
<input
type='submit'
value='Create Exercise Log'
className='btn btn-primary'
/>
</div>
</form>
</div>
);
}
}
export default CreateExercise;
解决方案
使用部分应用程序,在您的组件中创建一个函数,该函数接受一个字段名称,并返回一个设置状态的函数:
onChangeValue = field => e => {
this.setState({
[field]: e.target.value
});
};
用法:
onChangeUsername = onChangeValue('username');
onChangeDescription = onChangeValue('description');
onChangeDuration = onChangeValue('duration');
您进一步扩展了这个想法以支持onChangeDate
:
onChangeValue = (field, valueTransformer = e => e.target.value) => e => {
this.setState({
[field]: valueTransformer(e.target.value)
});
};
这不会改变其他on
函数,因为默认是 get e.target.value
。要使用onChangeDate
,我们现在可以更改valueTransformer
:
onChangeDate = onChangeValue('date', v => v);
推荐阅读
- file - Latex:如何将文本文件中的变量 URL 添加到生成的 PDF 文件中?
- php - WordPress:排队资源 - “句柄”的含义?
- c# - 需要删除通过 asp.net 发送的电子邮件中的附件
- php -
类别:示例 在模板中,不希望地将内容包装在标签
- c# - 使用 PrepareForSegue Xamarin.iOS 将数据从两方传输到另一方
- javascript - sql数据库状态改变时自动刷新页面
- kotlin - `equals(Any?): Boolean`的扩展函数覆盖
- reactjs - 单击按钮将页面滚动到子 React 组件
- html - CSS overflow-x:hidden 在移动设备上不起作用
- angular - 类型'可观察的
>' 不可分配给类型 'boolean | 网址树 | 可观察的 | 承诺 '