TypeError:无法读取未定义的属性“ validateName”

时间:2018-10-20 05:40:19

标签: javascript reactjs web-frontend

我是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
                }
            }
        }

请帮助我解决此问题

1 个答案:

答案 0 :(得分:1)

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

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

将其更改为

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

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

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

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

无论您在何处具有事件处理函数,都应将它们绑定到构造函数中,并使用如上所述的引用