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

时间:2018-06-26 06:56:06

标签: javascript html reactjs

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

我该怎么做?

<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>

4 个答案:

答案 0 :(得分:3)

您可以使用以下内联样式:

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>

答案 1 :(得分:1)

您可以按照以下步骤进行操作:

if let resumeDictionary = try? PropertyListSerialization.propertyList(from: resumeData, options: PropertyListSerialization.MutabilityOptions.mutableContainersAndLeaves, format: nil), var plist = resumeDictionary as? [String: Any] {

  guard let bytesReceived = plist["NSURLSessionResumeBytesReceived"] as? Int, let entityTag = plist["NSURLSessionResumeEntityTag"] as? String, let downloadUrl = plist["NSURLSessionDownloadURL"] as? String
  else {
    return
  }

  let headers = [
    "Range":"bytes=\(bytesReceived)-",
    "Etag": "\(entityTag)"]

  var newRequest = try! URLRequest.init(url: newPath, method: .get, headers: headers)
  let archivedData = NSKeyedArchiver.archivedData(withRootObject: newRequest)

  plist.updateValue(newPath, forKey: "NSURLSessionDownloadURL")
  plist["NSURLSessionResumeCurrentRequest"] = archivedData

  guard let updatedResumeData = try? PropertyListSerialization.data(fromPropertyList: plist, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)  else {
    return 
  }

  Alamofire.download(resumingWith: updatedResumeData).response(completionHandler: { (result) in
    //calling original requsest endpoint 
    })
 }

React将样式属性视为对象。因此,我们必须提供双引号“ {{}}”,并且在其中是我们的CSS代码。 另外,符号应为<h1 style={{color: 'red'}}>Hello world</h1> 。 例如camel-case

答案 2 :(得分:1)

您可以使用外部CSS文件,然后将其导入您的代码中

您还可以使用内联CSS

<NavLin / to="/home" activeStyle={{ color:'green', fontWeight: 'bold'}}> Home </NavLin>

样式对象可以在此处填充

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

答案 3 :(得分:0)

index.html中的

样式标记

<style>
  .textColor{
     color : 'red'
  }
<style>

使用:<h1 className="textColor">text colors</h1>

内联

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

使用样式对象

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