Ilj*_*lja 22 javascript reactjs
假设我有3个道具,我的基于类的组件需要和实现ie
<Component propOne={this.props.one} propTwo={this.props.two}>
{this.props.children}
</Component>
Run Code Online (Sandbox Code Playgroud)
我如何传递我原本不期望的任何其他道具,但是说使用我的组件的其他人会想要使用?
我刚在想
<Component propOne={this.props.one} propTwo={this.props.two} {...this.props} >
{this.props.children}
</Component>
Run Code Online (Sandbox Code Playgroud)
但我担心道具重复
Kou*_*sha 47
使用扩展运算符
const {propOne, propTwo, ...leftOver} = this.props;
// `leftOver` contains everything except `propOne` and `propTwo`
Run Code Online (Sandbox Code Playgroud)
所以你的例子将成为:
const {propOne, propTwo, children, ...props} = this.props;
<Component propOne={propOne} propTwo={propTwo} {...props}>
{children}
</Component>
Run Code Online (Sandbox Code Playgroud)
扩展运算符很棒,但令我惊讶的是我没有在教程中发现它,然后花了很长时间才找到描述它的可靠来源。如果您怀疑它是如何工作的,请参阅官方 ReactJS POD 中的详细信息,来自一篇名为JSX In Depth的小文章......
\n\n\n如果您已经将 props 作为对象,并且想要在 JSX 中传递它,则可以使用 ... 作为 \xe2\x80\x9cspread\xe2\x80\x9d 运算符来传递整个 props 对象。这两个组件是等效的:
\nRun Code Online (Sandbox Code Playgroud)\nreturn <Greeting firstName="Ben" lastName="Hector" />;\n}\n\nfunction App2() {\n const props = {firstName: \'Ben\', lastName: \'Hector\'};\n return <Greeting {...props} />;\n}```\n
当然,对于您的情况,您只想传递一些孩子......
\n\n\nRun Code Online (Sandbox Code Playgroud)\nconst Button = props => {\n const { kind, ...other } = props;\n const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";\n return <button className={className} {...other} />;\n};\n在上面的示例中,kind 属性被安全地使用,并且不会传递到 DOM 中的元素。所有其他道具都通过 ...other 对象传递,使得该组件非常灵活。您可以看到它传递了 onClick 和 Children 属性。
\n
来源:ReactJS.org:JSX 深入,指定 React 元素类型,传播属性。
\n对于您的具体情况...
\nconst {propOne, propTwo, ...newChildProps} = this.props;\n<Component\n propOne={this.props.one}\n propTwo={this.props.two}\n {...newChildProps}\n>{children}</Component>\nRun Code Online (Sandbox Code Playgroud)\n
\xe2\x9c\x85 这是我的做法:
\nexport default function Button(props) {\n const { children, label, ...rest } = props;\n \n return (\n <button\n {...rest}\n aria-label={label}\n >\n {children}\n </button>\n )\n}\nRun Code Online (Sandbox Code Playgroud)\n\xe2\x9c\xa8 请注意,有时您不需要与给定 prop 命名相同的属性,因此这里我将label其提取并传递给aria-label.