Material UI 5搭配styled-components时,.attrs的替代方案是什么?
在Material UI 5的styled方法中为组件添加默认className
当你使用@mui/material/styles中的styled方法时,有两种常用方式为生成的HTML元素添加默认className:
方式一:链式调用attrs方法
和原生styled-components的写法逻辑一致,你可以在styled组件定义完成后,链式调用attrs方法传入默认的className属性:
import { styled } from '@mui/material/styles'; export const Wrapper = styled('div', { name: 'form-builder', slot: 'form-builder', })` display: grid; grid-template-areas: 'components-list forms-list field-config-editor'; grid-template-columns: 300px 1fr 450px; `.attrs({ className: 'components-list column', });
这样每次渲染Wrapper组件时,生成的div元素都会自动带上components-list column类名。
方式二:在styled配置参数中指定attrs
你也可以将attrs直接嵌入到styled的第二个配置对象参数里:
import { styled } from '@mui/material/styles'; export const Wrapper = styled('div', { name: 'form-builder', slot: 'form-builder', attrs: { className: 'components-list column', }, })` display: grid; grid-template-areas: 'components-list forms-list field-config-editor'; grid-template-columns: 300px 1fr 450px; `;
如果需要根据组件props动态生成className,还可以把attrs设置为函数:
import { styled } from '@mui/material/styles'; export const Wrapper = styled('div', { name: 'form-builder', slot: 'form-builder', attrs: (props) => ({ className: `${props.customClass || 'components-list'} column`, }), })` display: grid; grid-template-areas: 'components-list forms-list field-config-editor'; grid-template-columns: 300px 1fr 450px; `;
另外,如果只是需要在使用组件时临时追加类名,直接给组件传入className属性即可,该类名会和默认类名共存:
<Wrapper className="custom-additional-class" />
内容的提问来源于stack exchange,提问作者Akshay Vijay Jain
相关产品推荐
相关产品推荐

