为什么React函数组件中bind绑定prop失效,箭头函数却正常运行?
你收到的报错翻译为:类型错误:_this.setErrorMessage 不是一个函数。(在执行 '_this.setErrorMessage('Username/password empty')' 时,'_this.setErrorMessage' 为 undefined)
问题原因
这个报错是函数组件特性和类组件特性混用导致的,核心问题有两个:
- 函数组件没有实例this指向:你在
renderSignInView函数组件内部执行.bind(this)时,这里的this在严格模式下是undefined,非严格模式下是全局对象,无论哪种都不会挂载你在函数内部声明的username、password、setErrorMessage等局部变量。 - state相关变量是函数作用域内的局部常量,不会自动绑定到this上:你在
onClickCheckLogin里试图通过this.setErrorMessage、this.username访问的属性根本不存在,自然会触发对应报错。
正确写法说明
你原本用箭头函数传参的写法是符合函数组件设计逻辑的:
箭头函数会捕获当前renderSignInView的作用域,直接把当前的username、password、setErrorMessage作为参数传递给校验函数,全程不需要依赖this指向,不会出现绑定失效的问题。
优化方案(避免内联箭头函数)
如果你觉得内联箭头函数写法不够整洁,可以直接把校验逻辑写在组件作用域内,不需要额外传参和绑定this:
import React, {useState} from 'react'; import { Linking, Alert } from 'react-native'; import UserSignInView from './UserSignInView'; import User from '../../User'; const renderSignInView = () => { const [errorMessage, setErrorMessage] = useState(''); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const checkLogin = () => { if(!!username && !!password) { console.log("yeee"); } else { console.log('doooo'); setErrorMessage('Username/password empty'); } } return ( <UserSignInView errorMessage = {errorMessage} setUsername = {setUsername} setPassword = {setPassword} checkLogin = {checkLogin} openPrivacyPolicy = {onClickOpenPrivacyPolicy} /> ) };
内容的提问来源于stack exchange,提问作者TruffelNL
相关产品推荐
相关产品推荐

