[英]console.log shows that the prop has attributes name and number, but they are undefined
So I have the following code, where I would like to return the number of pages in a book inside of the Part component in the return props.pages.所以我有以下代码,我想在返回 props.pages 的 Part 组件内返回一本书的页数。 The console.log(props) prints out the attributes of the book (name and pages). console.log(props) 打印出书籍的属性(名称和页数)。 However when accessing them in the Part component via props.pages or props.name it returns undefined?但是,当通过 props.pages 或 props.name 在 Part 组件中访问它们时,它返回 undefined?
How would I go about fixing this我将如何解决这个问题
const Part = (props) => {
console.log(props);
return <p>{props.pages}</p>;
};
const Content = (props) => {
console.log(props);
return <Part props={props} />;
};
const App = () => {
const book1 = {
name: "Harry Potter",
pages: 108,
};
return (
<div>
<Content book={book1} />
</div>
);
};
export default App;
You've wrapped the "props" in another "props".您已将“道具”包装在另一个“道具”中。 When you do this:当你这样做时:
<Content book={book1} />
The props
object in the Content
component has a property called book
. Content
组件中的props
对象有一个名为book
的属性。 So when you do this:所以当你这样做时:
<Part props={props} />
The props
object in the Part
component has a property called props
. Part
组件中的props
对象有一个名为props
的属性。 That property is an object with a property called book
.该属性是一个具有名为book
的属性的对象。 You'd need to reference that property:您需要引用该属性:
return <p>{props.props.pages}</p>;
Alternatively, you can pass the values more explicitly instead:或者,您可以更明确地传递值:
<Part pages={props.pages} />
Or spread the properties of the props
object to implicitly pass all of them:或者传播props
对象的属性以隐式传递所有这些属性:
<Part {...props} />
In either of these cases you'd be able to access the property directly:在任何一种情况下,您都可以直接访问该属性:
return <p>{props.pages}</p>;
Try this :尝试这个 :
const Part = (data) => {
const { props } = data;
return <p>{props.book.pages}</p>
};
Demo : https://codesandbox.io/s/vigorous-jepsen-lqjs01?file=/src/App.js:24-113
演示: https://codesandbox.io/s/vigorous-jepsen-lqjs01?file=/src/App.js:24-113
://codesandbox.io/s/vigorous-jepsen-lqjs01?file=/src/App.js:24-113
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.