码迷,mamicode.com
首页 > Web开发 > 详细

ReactJS表单handleChange

时间:2018-01-05 18:27:56      阅读:1646      评论:0      收藏:0      [点我收藏+]

标签:box   pre   string   tar   change   concat   cal   utc   str   

    handleInputChange = (event) => {
        const target = event.target;
        const type = target.type;
        const value = String.prototype.trim.call(target.value);
        const name = target.name;
        if (type === ‘checkbox‘) {
            if (this.state.formData[name] === undefined) { // 创建
                this.setState(() => ({
                    formData: Object.assign(this.state.formData, {
                        [name]: [value],
                    }),
                }));
            } else {
                const valueIndex = this.state.formData[name].indexOf(value);
                if (valueIndex < 0) { // 查找是否已经被勾选
                    this.setState((prevState) => ({
                        formData: Object.defineProperty(this.state.formData, [name], {
                            value: prevState.formData[name].concat([value]),
                        }),
                    }));
                } else {
                    const arr = this.state.formData[name];
                    arr.splice(valueIndex, 1); // 去掉已经选择的
                    this.setState(() => ({
                        formData: Object.defineProperty(this.state.formData, [name], {
                            value: arr,
                        }),
                    }));
                }
            }
        } else {
            this.setState(() => ({
                formData: Object.assign(this.state.formData, {
                    [name]: value,
                }),
            }));
        }
    }

 

ReactJS表单handleChange

标签:box   pre   string   tar   change   concat   cal   utc   str   

原文地址:https://www.cnblogs.com/biubiuxixiya/p/8206138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!