javascript - 类型错误 : Cannot read property 'validateName' of undefined

标签 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
                }
            }
        }

请帮我解决这个问题

最佳答案

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

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

更改为

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

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

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

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

同样,无论您有事件处理函数,都将它们绑定(bind)在构造函数中并使用上面提到的引用

关于javascript - 类型错误 : Cannot read property 'validateName' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52902772/

相关文章:

javascript - 如何将复杂样式(即样式表)作为 props 传递给 React 组件?

reactjs - 我应该使用一种或多种操作类型来表示此异步操作吗?

scala - 当我使用 Binding.scala 时,出现错误 `each instructions must be inside a SDE block` ,我该如何解决?

javascript - 根据高度 overflow hidden 元素

javascript - jquery val() 内部自定义函数

javascript - 检查 html 输入元素值的 if 语句

javascript - 在页面加载时更改 css

javascript - React Native 如何在组件之间传递数据

javascript - 如何在弹出窗口(模态)中聚焦输入

javascript - 使用 jQuery 在 Bootstrap Carousel 中的同一张幻灯片上显示多个元素