我开始学习 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;
这是我的 App 组件
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;
它没有给我正确的输出 为什么?