简体   繁体   English

使用字符串而不是 CSSProperties 在 React 中设置内联 styles

[英]Setting inline styles in React using strings and not CSSProperties

Is there any way to set an inline style in React without using CSSProperties ?有没有办法在不使用CSSProperties的情况下在 React 中设置内联样式?

I'm importing a bunch of SVGs that have styles defined inline in the regular fashion, with things like我正在导入一堆以常规方式内联定义 styles 的 SVG,例如

style="fill:#bfd9ff;"

To convert that to work in React, right now I'm changing it to:要将其转换为在 React 中工作,现在我将其更改为:

style={{fill: "#bfd9ff"}}

The thing is.. this is kind of a pain to do, even with regex (since not everything is the same format).问题是..这有点痛苦,即使使用正则表达式(因为并非所有内容都是相同的格式)。 I really wish I could just keep the strings as-is and not have to manually change each style attribute to a CSSProperties object.我真的希望我可以保持字符串不变,而不必手动将每个样式属性更改为CSSProperties object。

Is there an alternate attribute or something that I could use to make it easier?是否有替代属性或我可以用来使其更容易的东西?

I'm imagining something like styleString="fill:#bfd9ff" where setting that attribute would fill in the style tag of the generated DOM element with the provided string, because then I could just do a quick replace of style to styleString .我在想象类似styleString="fill:#bfd9ff"的东西,其中设置该属性将使用提供的字符串填充生成的 DOM 元素的style标记,因为这样我就可以快速将style替换为styleString But I've done a bit of searching and can't seem to find anything like this, is there no other way than to just manually set up all the styles?但是我做了一些搜索,似乎找不到这样的东西,除了手动设置所有 styles 之外,没有别的办法吗?

Have you tried importing your svgs as components?您是否尝试过将 svg 作为组件导入? That way you could keep them in .svg files and you can keep the usual style=... syntax.这样,您可以将它们保存在.svg文件中,并且可以保持通常的style=...语法。

// importing a logo SVG and embedding it in JSX
import { ReactComponent as Logo } from './logo.svg';
const MyComponent = () => {
  return (
     ...
     <Logo />
  );
}

See: https://medium.com/@rossbulat/working-with-svgs-in-react-d09d1602a219请参阅: https://medium.com/@rossbulat/working-with-svgs-in-react-d09d1602a219

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

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