首页 > 解决方案 > 为什么在调用的 React 函数组件中只使用 props?

问题描述

我正在学习 React,但我遇到了一个令人困惑的点。在编写函数组件时,我到处都在使用道具。

我总是使用props.profile它,它工作正常。但是在一个代码组件中,我必须编写 const profiles=props;并且它运行良好。

我尝试使用const profiles=props.profile;我也尝试return在“卡片”功能组件中使用内部

{props.profile.avatar_url}但他们都失败了

下面是我的代码,它工作正常

const Card=(props)=>{
  const profiles=props; //This I dont understand
  return(
    <div>
      <div>
        <img src={profiles.avatar_url} width="75px" alt="profile pic"/>
      </div>
      <div>
        <div>{profiles.name}</div>
        <div>{profiles.company}</div>
      </div>
    </div>
  );
}

const CardList=(props)=>{
  return(
    <div>
      {testDataArr.map(profile=><Card {...profile}/>)}
    </div>
  );
}

有人可以帮我理解为什么我不能使用const profiles=props.profile吗?

获得正确结果的其他方法是什么?

标签: javascriptreactjs

解决方案


你的testDataArr可能是这样

testDataArr = [{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""}]

现在当你这样做时,

{testDataArr.map(profile=><Card {...profile}/>)}

在这里profile = {avatar_url:"",name:"",company:""}

当你这样做时,

<Card {...profile}/>

相当于,

<Card avatar_url="" name="" company=""/>

在子组件中,当你这样做时,

const profiles=props;

这里props = {avatar_url:"",name:"",company:""}

所以你可以访问它的值,

props.avatar_url

props.name

props.company

但是当你这样做时,

const profiles=props.profile

profile对象中不存在密钥{avatar_url:"",name:"",company:""}并且失败。


推荐阅读