未捕获的TypeError:无法创建属性' \ tempFirstName'在字符串''

时间:2017-06-22 09:52:06

标签: reactjs

我在 ReactJS 应用中收到了这样的错误,

未捕获的TypeError:无法创建属性' \ tempFirstName'在字符串''

在我使用清除按钮清除文本框并尝试输入后,在浏览器控制台中显示此错误。

代码如下:

import React from 'react';
import fetch from 'isomorphic-fetch';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import FormErrors from './FormErrors.js';

export default class EmployeeRegister extends React.Component {

    constructor() {
        super();
        this.state = {
            empFirstName: ''     
        }
        this.handleChange = this.handleChange.bind(this);
        this.clearFields = this.clearFields.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;
        this.setState({[name]: value})
        });
    }

clearFields() {

        this.setState({empFirstName: ''})

    }

 render() {

        return (

            <div>

                <div className="row">
                    <div className="col-sm-12">
                        <h2>Employee Register Form</h2>
                    </div>
                </div>



                <form>

                    <div className="row">
                        <div className="col-sm-6">

                            <div className="form-group">
                                <label htmlFor="empFirstName">First Name : </label>
                                <input type="text" className="form-control" id="empFirstNameTxt" value={this.state.empFirstName}
                                       name="empFirstName"
                                       onChange={this.handleChange}/>
                            </div>

                        </div>

                    </div>



                    <div className="row">

                    <input type="submit" value="Submit" className="btn btn-primary" id="submitBtn" />
                             <input type="button" value="Clear"
                           className="btn btn-warning"
                           onClick={this.clearFields}/>


                    </div>


                </form>

            </div>



        );
    }
};

1 个答案:

答案 0 :(得分:1)

此处name的类型为const。现在将const更改为var。它应该工作

 var name = target.name;
        this.setState({[name]: value})
        });