在React中设置行内样式:

  1. 将元素的style prop设置为对象。
  2. 为元素的样式设置指定的属性和值。
  3. 比如说,<div style={{backgroundColor: 'salmon', color: 'white'}}>
// App.js

const App = () => {
  const stylesObj = {
    backgroundColor: 'lime',
    color: 'white',
  };

  const elementWidth = 150;

  return (
    <div>
      {/* 👇️ set inline styles directly */}
   {/* 👇️ 直接设置行内样式 */}
      <div style={{backgroundColor: 'salmon', color: 'white'}}>
        Some content
      </div>

      <br />

      {/* 👇️ set inline styles using an object variable */}
      {/* 👇️ 使用对象变量设置行内样式 */}
      <div style={stylesObj}>Some content</div>

      <br />

      {/* 👇️ set inline styles conditionally using a ternary */}
      {/* 👇️ 使用三元运算符设置行内样式 */}
      <div
        style={{
          backgroundColor: 'hi'.length === 2 ? 'violet' : 'mediumblue',
          color: 'hi'.length === 2 ? 'white' : 'mediumpurple',
        }}
      >
        Some content
      </div>

      <br />

      {/* 👇️ set inline styles interpolating a variable into a string */}
      {/* 👇️ 在字符串中插入变量,来设置行内样式 */
      <div
        style={{
          width: `${elementWidth}px`,
          backgroundColor: 'salmon',
          color: 'white',
        }}
      >
        Some content
      </div>
    </div>
  );
};

export default App;

 

方式

直接设置行内样式

第一个示例是直接在元素上设置行内样式。

<div style={{backgroundColor: 'salmon', color: 'white'}}>
  Some content
</div>

 

需要注意的是,当在style对象上设置样式时,多单词属性诸如background-color 需要设置为驼峰样式。style属性的值被包装在两对花括号中。

行内样式的第一对花括号标志着表达式的开始,第二对花括号是包含样式和值的对象。

提取到变量中

第二个示例将样式对象提取到一个变量中。

 

const App = () => {
  const stylesObj = {
    backgroundColor: 'lime',
    color: 'white',
  };

  return (
    <div>
      {/* 👇️ set inline styles using an object variable */}
      <div style={stylesObj}>Some content</div>
    </div>
  );
};

export default App;

当你有多个元素共享相同的样式时,你可以使用该方法。

三元运算符

在React中,可以使用三元运算符来有条件地设置行内样式。

<div
  style={{
    backgroundColor: 'hi'.length === 2 ? 'violet' : 'mediumblue',
    color: 'hi'.length === 2 ? 'white' : 'mediumpurple',
  }}
>
  Some content
</div>

 

三元运算符与if/else语法非常相似。

问号前的部分会被计算,如果它返回一个真值(truthy),运算符会返回冒号前的值,否则会返回冒号后的值。

示例中的三元运算符检查字符串hilength属性是否等于2 ,如果等于,则返回字符串violet作为backgroundColor属性的值;否则返回字符串mediumblue作为backgroundColor属性的值。

模板字符串

在设置行内样式时,还可以用字符串插入表达式或变量。

const App = () => {
  const elementWidth = 150;

  return (
    <div>
      {/* 👇️ set inline styles interpolating a variable into a string */}
      <div
        style={{
          width: `${elementWidth}px`,
          backgroundColor: 'salmon',
          color: 'white',
        }}
      >
        Some content
      </div>
    </div>
  );
};

export default App;

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐