[英]Add props as an HTML attribute in a React.js component
我最近开始使用 Next.js 和 Tailwindcss。 我想创建一个可以按如下方式使用的自定义组件 -
<CustomComponent> Hello World </CustomComponent>
在寻找如何使用它时,我遇到了一个答案,上面写着-
const CustomComponent = props => {
return (
<>
<div {...props} className="text-red-900" />
</>
)
}
在我的示例中, CustomComponent
将简单地将文本颜色设置为红色阴影。
我现在可以将此组件用作<CustomComponent> Hello World </CustomComponent>
。
我不明白的是这一行 - <div {...props} className="text-red-900" />
。 我在 reactjs 文档中找不到这样的东西。
这是将 props 作为 HTML 属性传递的合适方式吗? 它是如何工作的?
以下是等效组件:
const CustomComponent = (props) => {
return <div className="text-red-900" {...props} />;
};
// props={prop1,prop2,className}
const CustomComponent = ({ ...props }) => {
return <div className="text-red-900" {...props} />;
};
const CustomComponent = ({ prop1, prop2, className }) => {
// className will be overridden if its valid
return <div className="text-red-900" prop1={prop1} prop2={prop2} className={className} />;
};
请注意,最好在内联样式( className
)之后使用扩展语法(用于对象文字) ,这使其更通用。
至于为什么传播属性是有效的语法?
您在文档中解释了Spread Attributes ,请记住 JSX 被转换为React.createElement
,它接受props
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.