Javascript 如何在 React JS 中为文本设置颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51036625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set color to text in React JS
提问by Just Ahead
I just want to change color of text using style in tag
我只想使用标签中的样式更改文本的颜色
How can I do that?
我怎样才能做到这一点?
<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>
回答by pala?н
You can use inline-style like:
您可以使用内联样式,例如:
const element = <h1 style={{ color: 'red' }}>Hello world</h1>
or
或者
const hStyle = { color: 'red' };
const element = <h1 style={ hStyle }>Hello world</h1>
For more info:
欲了解更多信息:
Demo:
演示:
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>
回答by Rajat
You can use external css file and then import it in your code
您可以使用外部 css 文件,然后将其导入到您的代码中
You can also use Inline CSS
您还可以使用内联 CSS
<NavLin / to="/home" activeStyle={{ color:'green', fontWeight: 'bold'}}> Home </NavLin>
Object of style can be populated here
可以在此处填充样式对象
activeStyle={{ color:'green', fontWeight: 'bold'}}
回答by Ricks
You can do it like below :
你可以这样做:
<h1 style={{color: 'red'}}>Hello world</h1>
React treats style attribute as an object. So we have to provide double quotes "{{ }}" and inside that is our css code.
Also the notation should be camel-case.
e.g. {{backgroundColor: 'red'}}
React 将样式属性视为一个对象。所以我们必须提供双引号 "{{ }}" 并且里面是我们的 css 代码。符号也应该是camel-case. 例如{{backgroundColor: 'red'}}
回答by Revansiddh
style tagin index.html
index.html 中的样式标签
<style>
.textColor{
color : 'red'
}
<style>
Use : <h1 className="textColor">text colors</h1>
用 : <h1 className="textColor">text colors</h1>
Inline:
内联:
<h1 style={{ color: 'red' }}>inline styling</h1>
Using Style Object
使用样式对象
const styles= {
color: 'red',
};
<h1 style={styles}>Style obje</h1>

