javascript - 如何为不同的输入绑定多个 onChange 回调?
问题描述
我正在使用 ant design 制作一个不同的表单组件并尝试绑定几个不同的输入
这是代码:
this.state = {
title: '',
product: '',
options: 0,
price: 0,
}
onTitleChange = (e) => {
this.setState({
title: e.target.value
})
}
onProductChange = (e) => {
this.setState({
product: e.target.value
})
}
onHandleChange = value => {
this.setState({
priceOption: value
})
}
onNumberChange = e => {
this.setState({
price: e.target.value
})
}
<FormItemRow>
<Col span={24} style={colStyle}>
<FormItem label={'title'} colon={false} style={{ marginBottom: 0 }}>
{getFieldDecorator('title', {
rules: [
{ required: true, message: 'title is required' },
],
})(<Input onChange={this.onTitleChange}/>)}
</FormItem>
</Col>
</FormItemRow>
<FormItemRow>
<Col span={24} style={colStyle}>
<FormItem label={'product-number'} colon={false} style={{ marginBottom: 0 }}>
{getFieldDecorator('product-number', {
rules: [{ required: true, message: 'product-number is required' }],
})(<Input onChange={this.onProductChange}/>)}
</FormItem>
</Col>
</FormItemRow>
<FormItemRow>
<Col span={12} style={colStyle}>
<FormItem label={'options'} colon={false} style={{ marginBottom: 0 }}>
{getFieldDecorator('options', {
rules: [
{ required: true, message: 'options is required' },
],
})(<Select onChange={this.onHandleChange}>{this.handWashOptions(this.props.handWashOptions)}</Select>)}
</FormItem>
</Col>
<Col span={12} style={colStyle}>
<FormItem label={'price'} colon={false} style={{ marginBottom: 0 }}>
{getFieldDecorator('price', {
rules: [
{ required: true, message: 'price is required' },
],
})(<Input type="number" onChange={this.onNumberChange}/>)}
</FormItem>
</Col>
</FormItemRow>
标题和产品仅使用Input组件。
选项正在使用Select组件。
价格使用输入类型数字组件。
我认为在每个输入组件上使用不同的 onChange 回调是非常低效的。
有什么方法可以绑定一个 onChange 回调函数吗?
解决方案
您可以简单地制作一个通用函数handleChange,传递要更新的名称和值
handleChange(name,value){
this.setState({[name]: value})
}
并传递值来处理这样的变化
<Input onChange={(name,value)=>this.onTitleChange(name,value)}/>
您可以使用从目标e.target.value
获取value
,如果您需要对某些特定元素有不同的逻辑,那么您可以简单地在handleChange
推荐阅读
- azure - 如何使用 azure CLI 检查 azure 资源是否已在使用?
- python - pytorch中的autograd可以处理同一模块中层的重复使用吗?
- git - 为什么 github 有一个 pull request 号?
- android - 致命异常:尝试在空对象引用 getItemCount 上调用接口方法“int java.util.List.size()”
- python - 如何使用 tkinter python 拖动矩形中的全部内容?
- python - 替换文件中两个字符之间的字符串
- android - Flutter 如何平滑地为标记设置动画?
- google-analytics - 如何计算访问次数最多的页面,不包括 Google Analytics 上的目标页面访问?
- javascript - 多个键的 JSON 过滤运行缓慢
- database - MongoDB - 将两个集合嵌入到一个集合中