黑白梦黑白梦

  • 文章
  • 专栏
  • 文章
  • 专栏
全部文章

react 中指定 style 标签,动态设置内部样式

发布于 2021-08-31更新于 2022-06-02约 2 分钟

使用场景

当需要覆盖一些组件的内部样式,但又不方便写在 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')
);
目录
使用场景示例
上一篇使用 babel 7 后,解决老旧 npm 库对旧版 babel-core 的依赖问题下一篇cheerio 类 jq 语法进行访问与操作 html 文本

©2015-2026 黑白梦 粤ICP备15018165号

联系: heibaimeng@foxmail.com