ReactJS->“清除”输入表单的问题

问题描述 投票:0回答:1

我的表单很简单。每次我尝试填写表格时,其余字段都会清除。另外,验证错误显示在每个字段下方,而不仅仅是一个。如何解决这个问题?在执行任何操作之前的外观:https://i.imgur.com/zjGsNRL.png以及它如何处理错误数据:https://i.imgur.com/pSh6rFM.png

我的构造函数:

constructor(props) {
        super(props);
        this.state = {
            title: {
                text: ''
            },
            foods: [{
                text: '',
                kcal: '',
                protein: '',
                carbohydrate: '',
                fat: ''
            }],
        };

处理程序和验证f():

 handleKcalChange(event, index) {
        const foods = this.state.foods.slice();
        const value = event.target.value;


        foods[index] = {
            kcal: value,
            ...this.validateParam(value)
        }

        this.setState({
            foods: foods
        });
    }
 handleProteinChange(event, index) {
        const foods = this.state.foods.slice();
        const value = event.target.value;

        foods[index] = {
            protein: value,
            ...this.validateParam(value)
        }

        this.setState({
            foods: foods
        });
    }
validateParam = (paramNumber) => {
        if(paramNumber < 0) {
            return {
                validateStatus: 'error',
                errorMsg: 'Number can`t be smaller than 0.'
            }
        } else if(paramNumber > 1000) {
            return {
                validateStatus: 'error',
                errorMsg: 'Number is too big!'
            }
        } else {
            return {
                validateStatus: 'success',
                errorMsg: null
            }
        }
    }
javascript reactjs web
1个回答
0
投票

一个问题可能在handleKcalEvent中

foods[index] = {
            kcal: value,
            ...this.validateParam(value)
        }

您没有在索引处更改对象的kcal,而是将对象更改为仅具有kcal具有参数的新对象,从而擦除了所有其他信息(文本,脂肪,碳水化合物等)。

尝试类似

const current = foods[index];
foods[index] = {...current,
                kcal: value,
                ...this.validateParam(value)
            }
© www.soinside.com 2019 - 2024. All rights reserved.