【问题标题】:this.setState is not a function for textfieldthis.setState 不是文本字段的函数
【发布时间】:2016-01-05 01:02:03
【问题描述】:

在用户在文本字段中输入时尝试对文本字段进行验证。我想即时更改errorText 属性的状态。

我在尝试设置状态时收到错误 Uncaught TypeError: this.setState is not a function。相关代码如下。

export default class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            username: null,
            errorCopy: null
        };
    }
    handleChange(e) {
        this.setState({errorCopy: 'Generic error copy'});
    }
    render() {
        return(
            <TextField
                hintText="Username"
                value={this.state.username}
                onChange={this.handleChange}
                errorText={this.state.errorCopy} />
        )
    }
}

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    哎呀,在 ES6 中类绑定必须手动完成。

    需要在handleChange中添加.bind(this)

    export default class Login extends Component {
        constructor(props, context) {
            super(props, context);
            this.state = {
                username: null,
                errorCopy: null
            };
        }
        handleChange(e) {
            this.setState({errorCopy: 'Generic error copy'});
        }
        render() {
            return(
                <TextField
                    hintText="Username"
                    value={this.state.username}
                    onChange={this.handleChange.bind(this)}
                    errorText={this.state.errorCopy} />
            )
        }
    }
    

    【讨论】:

    • 不需要手动绑定,handleChange = (e) =&gt; {}也可以,但是自动绑定功能被去掉了。
    • 执行handleChange = (e) =&gt; { 在第一个等号上给了我一个意外的标记。使用 babel 和 webpack。
    • 你用的是哪个阶段的babel?
    • 使用 babel-loader 5.3.2 而使用 babel-core 5.4.0
    • 你甚至可以在构造函数中像this.handleChange = this.handleChange.bind(this)一样给出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2017-06-16
    • 2019-10-25
    • 2020-09-08
    相关资源
    最近更新 更多