当需要覆盖一些组件的内部样式,但又不方便写在 css 文件中,比如需要通过 props 动态传参进入设置时,就可以使用 style 标签来解决。
如果要使用 ant design 的 Rate 评分组件,希望能封装一个组件,可以传入 color 来设置颜色。假设不能通过 Rate 官方 api 配置的评星颜色的情况下,可以使用该方法来解决。
通过 https://ant.design/components/rate-cn/ 找到其中一个示例,点击“stackblitz打开”,进入在线编程界面。
const MyRate = ({ color }) => {
return (
<>
<Rate />
<style>
{`.ant-rate-star-full .anticon-star {
color: ${color};
}`}
</style>
</>
);
};
ReactDOM.render(<MyRate color="red" />, document.getElementById('container'));
然而,以上的做法是会污染到全局的样式,并且不同的组件之间样式也可能会相互影响。
可以通过给组件一个随机的类名,并为这个随机类名下的元素设置样式。
const MyRate = ({ color }) => {
const [componentNo, setComponentNo] = useState(0);
useEffect(() => {
setComponentNo(Math.floor(Math.random() * 100000) + 1);
}, []);
return (
<>
<Rate className={`my-rate-${componentNo}`} />
<style>
{`.my-rate-${componentNo} .ant-rate-star-full .anticon-star {
color: ${color};
}`}
</style>
</>
);
};
ReactDOM.render(
<div>
<MyRate color="red" />
<MyRate color="blue" />
</div>,
document.getElementById('container')
);