在 Person(Child Component) 函数中将 prop 作为参数传递时,为什么我们应该在花括号中编写 props?
应用程序.js
import React from 'react';
import Person from './Person';
const App = () => {
return (
<div>
<Person name={"John"} />
</div>
);
}
export default App;
人物.js
import React from 'react';
const Person = ({name}) => { //I am talking about this line
return (
<div>
<h1/>My name is {name}.</h1>
</div>
);
}
export default Person;
如果要传递的字符串道具是静态的 - 就像这里一样 - 没有必要。
<Person name="John" />
会工作得很好。
{}
只要要传递的值不是静态的,就需要s - 例如,当它来自变量时:
<Person name={nameFromState} />
{}
在将任何内容插入 JSX(道具之外)时,您还需要s,如您在
<h1/>My name is {name}.</h1>
这条线
const Person = ({name}) => {
只是解构,相当于
const Person = (props) => {
const { name } = props;
这相当于
const Person = (props) => {
const name = props.name;
所有这些可能性都可以正常工作,但有些人更喜欢在参数列表中进行解构以使事情更简洁。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句