简体   繁体   English

将自定义 html 属性设置为材质 ui 组件的子元素

[英]Set custom html attribute to child element of material ui component

I have to add the custom HTML5 attribute "data-metrics" to the span element, but I'm not sure how to achieve that using the ListItemText Material UI component.我必须将自定义 HTML5 属性“data-metrics”添加到 span 元素,但我不确定如何使用 ListItemText Material UI 组件来实现。 Component API Documentation: https://mui.com/material-ui/api/list-item-text/组件 API 文档: https://mui.com/material-ui/api/list-item-text/

This is my code at the moment:这是我目前的代码:

<li>
  <ListItem button key={`list_item_${index}`}
    component={Link} to={data.url}
    activeClassName={classes.activeLink} partiallyActive={true}
    focusVisibleClassName={classes.buttonOnFocus}>
     <ListItemText primary={data.name} 
       data-metrics={`{"btnname":"${data.name.toLowerCase()}"}`}/>
  </ListItem>
</li>

And this is what it is generating: Attribute is being set to div element instead of span(child)这就是它正在生成的内容:属性被设置为 div 元素而不是 span(child)

Note the data-metrics attribute is being set to the div element instead of the span.注意 data-metrics 属性被设置为 div 元素而不是 span。

You can use useRef hook for this purpose, after you found an element in your ref.current object you can invoke ref.current.setAttribute("data-metrics", VALUE) It forwards ref to a root element为此,您可以使用 useRef 挂钩,在 ref.current object 中找到一个元素后,您可以调用ref.current.setAttribute("data-metrics", VALUE)它将 ref 转发到根元素

I think you need to use the "primaryTypographyProps" prop inside the component.我认为您需要在组件内使用“primaryTypographyProps”道具。 At least I think that's what the docs are saying.至少我认为这是文档所说的。

I think you need to pass it an object like so:我认为你需要像这样传递一个 object :

<ListItemText primaryTypographyProps={{"data-metrics": "test"}} />

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

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