为什么我们在子组件中使用时要在花括号中写道具
why should we write props in curly braces while using in child component
在 Person(Child Component) 函数中将 prop 作为参数传递时,为什么我们应该将 props 写在花括号中?
App.js
import React from 'react';
import Person from './Person';
const App = () => {
return (
<div>
<Person name={"John"} />
</div>
);
}
export default App;
Person.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(props 之外)时,您还需要 {}
s,如您在
中所见
<h1/>My name is {name}.</h1>
这一行
const Person = ({name}) => {
只是解构,相当于
const Person = (props) => {
const { name } = props;
相当于
const Person = (props) => {
const name = props.name;
所有这些可能性都很好,但有些人更喜欢在参数列表中解构以使事情更简洁。
使用 {}
在 JSX 中使用 javascript,方法是将其包裹在大括号中。您可以在文档 reactjs
中阅读更多内容:https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx
在 Person(Child Component) 函数中将 prop 作为参数传递时,为什么我们应该将 props 写在花括号中?
App.js
import React from 'react';
import Person from './Person';
const App = () => {
return (
<div>
<Person name={"John"} />
</div>
);
}
export default App;
Person.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(props 之外)时,您还需要 {}
s,如您在
<h1/>My name is {name}.</h1>
这一行
const Person = ({name}) => {
只是解构,相当于
const Person = (props) => {
const { name } = props;
相当于
const Person = (props) => {
const name = props.name;
所有这些可能性都很好,但有些人更喜欢在参数列表中解构以使事情更简洁。
使用 {}
在 JSX 中使用 javascript,方法是将其包裹在大括号中。您可以在文档 reactjs
中阅读更多内容:https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx