如何在React JS中设置文本颜色

29

我只想使用标签中的样式改变文本的颜色

我应该怎么做?

<div id="root"></div><br>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script><br>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script><br>

<script type="text/babel">
const rootElement = document.getElementById('root');<br>
const element = <h1>Hello world</h1><br>

ReactDOM.render(element, rootElement);<br>
</script>

1
你的意思是内联样式表吗?例如:<h1 style="color: red;">Hello world</h1> - Ashar Dweedar
@AsharDweedar 是的,但这在React JS中能行吗? - Just Ahead
5个回答

38

您可以使用内联样式,例如:

const element = <h1 style={{ color: 'red' }}>Hello world</h1>

或者
const hStyle = { color: 'red' };
const element = <h1 style={ hStyle }>Hello world</h1>

更多信息:

演示:

const rootElement = document.getElementById('root');
const element = <h1 style={{ color: 'red' }}>Hello world</h1>;
ReactDOM.render(element, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


第二个可用!谢谢。但为什么第一个不起作用? - Just Ahead
1
我错过了一个额外的括号。现在应该可以工作了。 - palaѕн

7
在index.html中的style标签
<style>
  .textColor{
     color : 'red'
  }
<style>

使用:<h1 className="textColor">文本颜色</h1>

内联:

<h1 style={{ color: 'red' }}>inline styling</h1>

使用样式对象

const styles= {
    color: 'red',
};
<h1 style={styles}>Style obje</h1>

3
你可以使用外部CSS文件,然后在代码中导入它。
你也可以使用内联CSS。
<NavLin / to="/home" activeStyle={{ color:'green', fontWeight: 'bold'}}> Home </NavLin>

样式对象可以在此处填充

activeStyle={{ color:'green', fontWeight: 'bold'}}

当你回答问题时,请尽量对代码进行格式化。以下是格式化代码的指南: https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks - Revansiddh

2
您可以按照以下方式进行操作:
<h1 style={{color: 'red'}}>Hello world</h1>

React将样式属性视为对象。因此,我们必须提供双引号 "{{ }}",并在其中放置我们的CSS代码。 此外,表示法应该是驼峰式。 例如:{{backgroundColor:'red'}}


1
const App = () => {
  return (
    <div>
      <p style={{fontSize: '2rem'}}>
        Hi {' '}
        <span style={{color: 'white', backgroundColor: 'green'}}>Hello</span>{' '}
        text
      </p>
    </div>
  );
};

export default App;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接