React(13)style 和 class

x33g5p2x  于2022-03-06 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(540)

20、style 写法

JSX里,写 style 属性,有几点需要注意:

  1. 以 k-v (对象)形式来写 style 属性(如果直接写在 html 标签里,容易以为是双大括号,事实上还是单大括号);
  2. key 使用驼峰写法;
  3. 值是字符串;
  4. 如果想混合多个属性,需要先通过例如 Object.assign() 将其混合为一个对象,再使用。 不能 使用数组或写 2 个 style={} 来实现;

示例代码:

  1. class StyleDemo extends React.Component {
  2. render() {
  3. let style = {
  4. fontSize: '100px',
  5. color: 'red'
  6. }
  7. return <div style={style}>
  8. 这是一段红色文字
  9. </div>
  10. }
  11. }

21、class 写法

有几点注意:

  1. 写在标签里的时候,不是 class = "xxx", 而是 className = "xxx"
  2. 值是字符串,自行拼空格;

示例代码:

  1. class StyleDemo extends React.Component {
  2. render() {
  3. let myClass = 'abc def'
  4. return <div className={myClass}>
  5. 这是一段红色文字
  6. </div>
  7. }
  8. }

原因:

警告:

因为 JSX 的特性更接近 JavaScript 而不是 HTML , 所以 React DOM 使用 camelCase 小驼峰命名 来定义属性的名称,而不是使用 HTML 的属性名称。

例如,class 变成了 className,而 tabindex 则对应着 tabIndex.

相关文章