You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中如何在子组件通过解构获取对象方法并解决报错

问题解决指南

核心错误原因

你遇到的ReferenceError源于两个问题:

  1. person对象的getFullName方法中,直接使用firstName和lastName,未通过this引用对象自身属性,JS引擎会在全局作用域查找这些变量,导致找不到。
  2. 即便修复了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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:01:00