React onClick报错:Cannot read property 'bind' of undefined 求助
解决React中onClick绑定报错:Cannot read property 'bind' of undefined
这个错误的核心原因很明确:你的组件实例找不到logOut方法,导致this.logOut是undefined,自然没法调用bind方法。我给你分两种组件类型来提供解决方案,顺便修复你代码里的小细节:
一、如果你用的是类组件
方案1:用箭头函数定义方法(推荐)
箭头函数会自动绑定组件实例的this,不需要手动调用bind,写法更简洁:
class YourAuthComponent extends React.Component { // 用箭头函数定义实例方法 logOut = () => { Auth.signOut() .then(data => console.log('登出成功')) // 这里你原来写的`logout`是未定义变量,要改成字符串或对应数据 .catch(err => console.log('登出失败:', err)); } render() { // 直接传方法即可,无需bind return <button onClick={this.logOut}>LogOut</button>; } }
方案2:在构造函数中提前绑定this
如果习惯用普通函数定义方法,可以在组件构造函数里提前把this绑定好,避免每次render都重新bind:
class YourAuthComponent extends React.Component { constructor(props) { super(props); // 提前绑定this到logOut方法 this.logOut = this.logOut.bind(this); } logOut() { Auth.signOut() .then(data => console.log('登出成功')) .catch(err => console.log('登出失败:', err)); } render() { return <button onClick={this.logOut}>LogOut</button>; } }
二、如果你用的是函数组件
函数组件里没有this对象,直接定义函数并传入onClick即可:
function YourAuthComponent() { const logOut = () => { Auth.signOut() .then(data => console.log('登出成功')) .catch(err => console.log('登出失败:', err)); } // 直接传logOut函数,不用加this return <button onClick={logOut}>LogOut</button>; }
另外要注意:你原来的logOut函数里,.then(data => console.log(logout))这一行的logout是未定义的变量,运行时会触发另一个错误,一定要改成字符串(比如'登出成功')或者你想打印的具体数据哦。
内容的提问来源于stack exchange,提问作者Samuel Gray
相关产品推荐
相关产品推荐

