首页 > 解决方案 > 如何为不同的输入绑定多个 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 回调函数吗?

标签: javascriptreactjsantd

解决方案


您可以简单地制作一个通用函数handleChange,传递要更新的名称和值

 handleChange(name,value){
   this.setState({[name]: value})
 }

并传递值来处理这样的变化

<Input onChange={(name,value)=>this.onTitleChange(name,value)}/>

您可以使用从目标e.target.value获取value,如果您需要对某些特定元素有不同的逻辑,那么您可以简单地在handleChange


推荐阅读