TypeError: Cannot read property 'validateName' of undefined

TypeError: Cannot read property 'validateName' of undefined

我是 ReactJs 的新手。 在我的应用程序中,我插入了以下代码来验证 textArea,但是当我在上面键入时,它会抛出以下错误。

NewBrand.js:67 Uncaught TypeError: Cannot read property 'validateName' of undefined
        at handleNameChange (NewBrand.js:67)
        at TextArea._this.handleTextareaChange (TextArea.js:94)
        at HTMLUnknownElement.callCallback (react-dom.development.js:100)
        at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
        at Object.invokeGuardedCallback (react-dom.development.js:187)
        at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:201)
        at executeDispatch (react-dom.development.js:461)
        at executeDispatchesInOrder (react-dom.development.js:483)
        at executeDispatchesAndRelease (react-dom.development.js:581)
        at executeDispatchesAndReleaseTopLevel (react-dom.development.js:592)

我的代码如下所示:

    handleNameChange(event) {
        const value = event.target.value;
        this.setState({
        name: {
            text: value,
            ...this.validateName(value)
        }
    });

    }

    isFormInvalid() {
        if(this.state.name.validateStatus !== 'success') {
            return true;
        }
    }

  validateName = (nameText) => {
            if(nameText.length === 0) {
                return {
                    validateStatus: 'error',
                    errorMsg: 'Please enter the Brand name!'
                }
            } else if (nameText.length > POLL_QUESTION_MAX_LENGTH) {
                return {
                    validateStatus: 'error',
                    errorMsg: `Name is too long (Maximum ${POLL_QUESTION_MAX_LENGTH} characters allowed)`
                }
            } else {
                return {
                    validateStatus: 'success',
                    errorMsg: null
                }
            }
        }

请帮我解决这个问题

当您连接更改处理程序(可能在您的渲染方法中)时,您的 jsx 看起来像这样

<textarea onChange={ this.handleNameChange } ...

改为

constructor(props){
  super(props);
  this.handleNameChange = this.handleNameChange.bind(this);
}

<textarea onChange={this.handleNameChange} ...

这确保 this 在更改回调运行时仍然引用 Component 对象。

请注意,不建议您直接在 render 中或组件中除构造函数之外的任何其他位置绑定函数。因为在 render 中绑定会导致每次组件渲染时在 bundle 文件中创建一个新函数,所以我们不建议这样做。

同样明智的是,只要你有事件处理函数,就可以将它们绑定到构造函数中,并像上面提到的那样使用引用