简体   繁体   English

反应更改div内所有子项的字体文本颜色

[英]React change font text color of all children inside div

I have render function set up something like this我已经设置了类似这样的渲染功能

<div
  dangerouslySetInnerHTML={{
     __html: page.content.rendered
   }}
/>

I get the page as prop from external api and page.content.rendered will be html in string form, something like this :我从外部 api 获取页面作为道具, page.content.rendered将是字符串形式的 html,如下所示:

<div>
  <h2> this is title </h2>
  <p> hello </p>
</div>

is there a way to change the text color of all children inside the div element?有没有办法改变 div 元素内所有子元素的文本颜色?

I tried adding color: "somecolor" to the outer div element, but nothing has changed.我尝试将 color: "somecolor" 添加到外部 div 元素,但没有任何改变。

<div style={{"color": "red"}}>
  <h2> this is title </h2>
  <p> hello </p>
</div>

You can style any parent element and it will apply to its children.您可以设置任何父元素的样式,它将应用于其子元素。 https://reactjs.org/docs/dom-elements.html#style https://reactjs.org/docs/dom-elements.html#style

For example:例如:

<div
  style={{color:'red'}}
  dangerouslySetInnerHTML={{
     __html: page.content.rendered
   }}
/>

There are many styling solutions that perform better and are well supported by the community: https://reactjs.org/docs/faq-styling.html有许多样式解决方案性能更好,并得到社区的大力支持: https : //reactjs.org/docs/faq-styling.html

Styling in JSX is done the same way as in HTML, you can either create the class in an external CSS file and do something like this: JSX 中的样式与 HTML 中的样式相同,您可以在外部 CSS 文件中创建类并执行以下操作:

import './style.css';

<div className='.myClass'
    dangerouslySetInnerHTML={{
    __html: page.content.rendered
   }}
/>

or you can do inline styling like this:或者你可以做这样的内联样式:

<div style={{color:'red'}}
    dangerouslySetInnerHTML={{
    __html: page.content.rendered
   }}
/>

Using inline styling in React is very strange in my opinion.在我看来,在 React 中使用内联样式非常奇怪。 I prefer to import a CSS file or use a library like Tachyons and use JSX className.我更喜欢导入 CSS 文件或使用像 Tachyons 这样的库并使用 JSX className。

You can find more help from a similar post here .您可以在此处的类似帖子中找到更多帮助。

I had a similar issue.我有一个类似的问题。 In my case i had to change the color from white to black.就我而言,我不得不将颜色从白色更改为黑色。 since the html content already have color specified i was not able to change the color with just using the div's style property由于 html 内容已经指定了颜色,因此我无法仅使用 div 的样式属性来更改颜色

I had to remove the color from the html content and to add black color using Js我不得不从 html 内容中删除颜色并使用 Js 添加黑色

Below could change the text color from white to black if the content already have text color如果内容已经有文本颜色,下面可以将文本颜色从白色更改为黑色

<div
    dangerouslySetInnerHTML={{
    __html: page.content.rendered.split("rgb(255,255,255)").join("rgb(0,0,0)")
   }}
/>

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

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