我开始学习React js,已经学到了解构props的知识点。通常我们会解构props然后像下面Greet组件的代码一样使用它的属性:
import React from "react";
const Greet = props => {
const { name, heroName } = props; //here I destructured it
return (
<div>
<h1>
Hello {name} a.k.a {heroName}
</h1>{" "}
// and then use simply name and heroName
</div>
);
};
export default Greet;
这是我的应用组件
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import Greet from "./components/Greet";
function App() {
return (
<div className="App">
<Greet name="kaptan" heroName=" ek" />
</div>
);
}
export default App;
在我继续创建一个名为Person和NameList的组件后,上述代码能够正常工作。以下是我的NameList组件:
import React from "react";
import Person from "./Person";
function NameList() {
const persons = [
{
id: 1,
name: "kaptan",
age: 30,
skill: "react"
},
{
id: 2,
name: "rinku",
age: 29,
skill: "java"
},
{
id: 3,
name: "ankit",
age: 39,
skill: "vue"
}
];
const personsList = persons.map(person => <Person person={person} />);
return <div>{personsList}</div>;
}
export default NameList;
这是我的人(Person)组件
import React from "react";
const Person = ({ person }) => {
// here i need to destructure person object
return (
<div>
<h2>
I am {person.name},My age is {person.age},I know {person.skill}
</h2>
</div>
);
};
export default Person;
那么我的问题是:为什么在Person组件中我不能像在Greet组件中那样解构呢?
就像这样
import React from "react";
const Person = props => {
const { name, age, skill } = props;
return (
<div>
<h2>
I am {name},My age is {age},I know {skill}
</h2>
</div>
);
};
export default Person;
它为什么不能给我正确的输出?