您是否在寻找 ES6 命名参数语法(仅仅是解构)?
const ChildComponent = ({ propName }) => (
<div>
<h1>Child Component</h1>
</div>
)
const ChildComponent = (props) => ( // without named arguments
<div>
<h1>Child Component</h1>
</div>
)
根据您是否为组件指定了 context,您的函数还有第二个参数(可选)。
也许链接到docs 会更有帮助。正如第一篇关于功能组件的文章所述。传递给组件的任何道具都表示为作为第一个参数传递给功能组件的对象。
更进一步,关于 jsx 中的扩展符号。
当你写在一个组件中时:
<Child prop1={value1} prop2={value2} />
您的组件将收到一个普通对象,如下所示:
{ prop1: value1, prop2: value2 }
(注意它不是 Map,而是一个只有字符串作为键的对象)。
因此,当您将 spread 语法与 JS 对象一起使用时,它实际上是一个快捷方式
const object = { key1: value1, key2: value2 }
<Component {...object}/>
相当于
<Component key1={value1} key2={value2} />
并实际编译为
return React.createElement(Component, object); // second arg is props
你当然可以使用第二种语法,但要注意顺序。更具体的语法 (prop=value) 必须在最后:更具体的指令在最后。
如果你这样做:
<Component key={value} {...props} />
编译成
React.createElement(Component, _extends({ key: value }, props));
如果你这样做(你可能应该这样做)
<Component {...props} key={value} />
编译成
React.createElement(Component, _extends(props, { key: value }));
extends 是 *Object.assign (如果不存在,则为 polyfill)。
为了更进一步,我真的建议花一些时间来观察 Babel 的输出及其online editor。这对于理解 jsx 是如何工作的,以及更一般地如何使用 ES5 工具实现 es6 语法非常有趣。