如何添加一个 classname/id 到 React-Bootstrap 组件?

How to add a classname/id to React-Bootstrap Component?

假设我们正在使用 React 中的 Row-Bootstrap...我们如何在不使用包装器或内部元素的情况下设置它的样式:

<Row>
  <div className='some-style'>
   ...
</Row>

理想情况下,我们可以这样做:

<Row className='some-style'> 
  ...
</Row>

但这不起作用,我认为这是因为 React-Bootstrap 不知道 className<Row> 组件中的什么位置(它应该只设置 <div> 具有行样式)。

如果您查看组件的 code,您会发现它使用传递给它的 className 道具与 row class 结合使用以获得classes 的结果集(<Row className="aaa bbb"... 有效)。此外,如果您提供 id<Row id="444" ... 这样的道具,它实际上会为元素设置 id 属性。

第一种方式是使用道具:

<Row id = "someRandomID">

那么在定义中,你可以使用:

const Row = props  => {
    <div id = {props.id}> something </div>
}

同样可以用 class 来完成,在上面的例子中用 className 替换 id


你也可以使用 react-html-id,那是一个 npm 包。 这是一个 npm 包,允许您为组件使用唯一的 html ID,而不依赖于其他库。

参考:react-html-id