javascript - 为什么在调用的 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
吗?
获得正确结果的其他方法是什么?
解决方案
你的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:""}
并且失败。
推荐阅读
- amazon-web-services - 创建反应应用程序“主页”:“。” 使用 aws api 网关时不使用来自 index.html 的正确相对路径
- json - Postgres jsonb 数据类型需要在插入/更新时序列化,但会自动反序列化
- php - JS AJAX POST 到 PHP,编辑 JSON 文件给出错误
- jquery - jquery 被另一个处理程序覆盖
- c++ - 如何在存储抽象基类引用的泛型上使用每个循环?
- ip-address - ping ip 脚本中的最大执行时间超过 300 秒
- c++ - 为什么微控制器用户手册中没有定义堆栈和堆大小?
- python - wpa_supplicant 没有接口(pydbus)
- ios - 启动基于文档的 SwiftUI 应用程序时的入职屏幕
- string - 错误的unicode字符串,看起来一样但本质不一样