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