[英]Why can't I access the props directly in Child Component?
I have stored the data in a file (details.js) as a JavaScript Object, then I'm trying to pass it as a prop from MainComponent to ChildComponent.我已将数据作为 JavaScript Object 存储在文件(details.js)中,然后我试图将其作为道具从 MainComponent 传递给 ChildComponent。 Well the prop is accessible in ChildComponent but I could access it with
props.ChildDetails[0].name
instead of props.name
directly as shown in the Official documentation好吧,道具可以在 ChildComponent 中访问,但我可以使用
props.ChildDetails[0].name
而不是props.name
直接访问它,如官方文档中所示
What's incorrect in my code?我的代码有什么不正确的地方?
details.js细节.js
export const DETAILS=[
{
id:0,
profile:'/assests/images/john.png',
name:'John Doe',
}
]
MainComponent.js MainComponent.js
import React,{useState} from 'react';
import Child from './ChildComponent';
import {DETAILS} from '../Shared/details';
function MainComponent(){
return(
<>
<Child ChildDetails={DETAILS}/>
</>
);
}
export default MainComponent;
ChildComponent.js ChildComponent.js
import React from 'react';
function ChildComponent(props){
console.log(props.name) //Output:undefined
console.log(props.ChildDetails[0].name) //Output:John Doe
return(
<div></div>
);
}
export default ChildComponent;
Because Details is object.因为详细信息是 object。 Try something like:
尝试类似:
function ChildComponent({ ChildDetails }){
const { name } = ChildDetails[0]
...
}
That's not even React.这甚至不是 React。 That's JavaScript
那是 JavaScript
Edit .编辑. Oops.
哎呀。 People said that's an array.
人们说那是一个数组。 I thought it's just an object.
我以为它只是一个 object。 Fixed code a bit
固定代码一点
here is where you passed the object这是您通过 object 的地方
<Child ChildDetails={DETAILS}/>
and here is how you tried to use it这是您尝试使用它的方式
console.log(props.name) //Output:undefined
since you defined the name as ChildDetails
there is no such thing as props.name instead you must say由于您将名称定义为
ChildDetails
,因此没有 props.name 这样的东西,您必须说
console.log(props.ChildDetails)
and if you want to get access to an name
you should declare the index if not react does not know which index you want to use, so as you did before如果你想访问一个
name
,你应该声明索引如果没有反应不知道你想使用哪个索引,就像你之前做的那样
props.ChildDetails[0].name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.