我的组件中的这个 prop 语法是什么?
What is this prop syntax in my component?
我有以下代码:
const cEditor = (onUpdate, props) => (<SelectEditor onUpdate=(onUpdate) {...props} />);
{...props}
正在做什么?似乎它正在将 props 传递给组件。这个语法是什么意思?
这是使用 spread syntax to "spread" the props to the component. Per the React documentation:
Spread Attributes
If you already have props
as an object, and you want to pass it in JSX, you can use ...
as a "spread" operator to pass the whole props object. These two components are equivalent:
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.
因此,如果您有一个以 props 作为键并将 prop 值作为值的对象,您可以使用传播语法将它们传播到组件。这两个组件是相同的:
const props = {
a: 5,
b: "string"
}
<Example {...props} />
等同于:
<Example a={5} b={"string"} />
在您的例子中,函数 cEditor
中的 props
是一个对象,将所有道具和道具值分别作为键和值。然后,那些 props 和 prop 值被传递给 <SelectEditor>
,除了 onUpdate
是单独传递的
(但如果 props
具有 onUpdate
键和值,则被覆盖)。
我有以下代码:
const cEditor = (onUpdate, props) => (<SelectEditor onUpdate=(onUpdate) {...props} />);
{...props}
正在做什么?似乎它正在将 props 传递给组件。这个语法是什么意思?
这是使用 spread syntax to "spread" the props to the component. Per the React documentation:
Spread Attributes
If you already have
props
as an object, and you want to pass it in JSX, you can use...
as a "spread" operator to pass the whole props object. These two components are equivalent:function App1() { return <Greeting firstName="Ben" lastName="Hector" />; } function App2() { const props = {firstName: 'Ben', lastName: 'Hector'}; return <Greeting {...props} />; }
Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.
因此,如果您有一个以 props 作为键并将 prop 值作为值的对象,您可以使用传播语法将它们传播到组件。这两个组件是相同的:
const props = {
a: 5,
b: "string"
}
<Example {...props} />
等同于:
<Example a={5} b={"string"} />
在您的例子中,函数 cEditor
中的 props
是一个对象,将所有道具和道具值分别作为键和值。然后,那些 props 和 prop 值被传递给 <SelectEditor>
,除了 onUpdate
是单独传递的
(但如果 props
具有 onUpdate
键和值,则被覆盖)。