简体   繁体   English

在 React.js 组件中添加 props 作为 HTML 属性

[英]Add props as an HTML attribute in a React.js component

I recently started using Next.js and Tailwindcss.我最近开始使用 Next.js 和 Tailwindcss。 I want to create a custom component that can be used as follows -我想创建一个可以按如下方式使用的自定义组件 -

<CustomComponent> Hello World </CustomComponent>

While searching for how to use this, I came across an answer which said -在寻找如何使用它时,我遇到了一个答案,上面写着-

const CustomComponent = props => {
  return (
    <>
      <div {...props} className="text-red-900" />
    </>
  )
}

In my example, the CustomComponent will simple make the text-color to a shade of red.在我的示例中, CustomComponent将简单地将文本颜色设置为红色阴影。

I can now use this component as <CustomComponent> Hello World </CustomComponent> .我现在可以将此组件用作<CustomComponent> Hello World </CustomComponent>

What I don't understand is this line - <div {...props} className="text-red-900" /> .我不明白的是这一行 - <div {...props} className="text-red-900" /> I couldn't find anything like this in the reactjs docs.我在 reactjs 文档中找不到这样的东西。

Is this an appropriate way of passing props as HTML attributes?这是将 props 作为 HTML 属性传递的合适方式吗? How does it work?它是如何工作的?

Here are equivalent components:以下是等效组件:

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} />;
};

Note that better to use spread syntax (for object literals) after the inline style ( className ) which makes it more generic.请注意,最好在内联样式( className之后使用扩展语法(用于对象文字) 这使其更通用。

As for why spreading the property is a valid syntax ?至于为什么传播属性是有效的语法

You have a Spread Attributes explained in the docs, remember that JSX is converted to React.createElement which accepts the props as an argument.您在文档中解释Spread Attributes ,请记住 JSX 被转换为React.createElement ,它接受props作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM