首页 > Web开发 > 详细

ReactJS表单handleChange

时间:2018-01-05 18:17:23      阅读:314      评论:0      收藏:0      [点我收藏+]
    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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!