1

在用户输入文本字段时尝试对文本字段进行验证。我想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} />
        )
    }
}
4

1 回答 1

3

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

需要添加.bind(this)到handleChange

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} />
        )
    }
}
于 2015-10-07T17:11:19.520 回答