React.js中如何在子组件通过解构获取对象方法并解决报错
问题解决指南
核心错误原因
你遇到的ReferenceError源于两个问题:
person对象的getFullName方法中,直接使用firstName和lastName,未通过this引用对象自身属性,JS引擎会在全局作用域查找这些变量,导致找不到。- 即便修复了
this引用,从props.person中单独解构出getFullName后调用,会丢失原对象的上下文,this指向undefined(严格模式下),依然报错。
分步解决
1. 修复对象方法的属性引用
修改person对象,在方法中用this访问自身属性:
const person = { id: 1, firstName: "John", lastName: "Smith", getFullName: function() { return `${this.firstName} ${this.lastName}`; } }
2. 解决this丢失问题
提供两种可行方案:
方案一:保留对象上下文调用方法
不单独解构getFullName,直接通过原person对象调用:
const Person = (props) => { const { id, firstName, lastName } = props.person return ( <> <div>{ id }</div> <div>{ firstName } { lastName }</div> <div>{ props.person.getFullName() }</div> </> ) }
方案二:手动绑定this到原对象
如果一定要解构方法,调用时通过bind绑定原对象的上下文:
const Person = (props) => { const { id, firstName, lastName, getFullName } = props.person // 提前绑定this const getFullNameBound = getFullName.bind(props.person) return ( <> <div>{ id }</div> <div>{ firstName } { lastName }</div> <div>{ getFullNameBound() }</div> </> ) }
或者直接在调用时用call:
<div>{ getFullName.call(props.person) }</div>
内容的提问来源于stack exchange,提问作者T'sen Ang
相关产品推荐
相关产品推荐

