React 中的字符串插值(附示例)

在 React 中使用模板文字进行字符串插值,例如 <div className={text-white ${myClass}}>。 模板文字用反引号分隔,并允许我们使用美元符号和大括号 ${expression} 语法嵌入变量和表达式。

import './App.css';

export default function App() {
  const myClass = 'bg-salmon';

  const name = 'James Doe';

  const num = 30;
  return (
    <div>
      <div className={`text-white ${myClass}`}>Some content here</div>

      <br />

      <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}>
        Some content here
      </div>

      <h2>Hello {name}</h2>

      <h2
        style={{
          padding: `${num + num}px`,
          backgroundColor: 'lime',
        }}
      >
        30 + 30 = {num + num}
      </h2>
    </div>
  );
}

这是示例的 CSS。

App.css

.bg-salmon {
  background-color: salmon;
}

.text-white {
  color: white;
}

我们可以使用模板文字在字符串中插入变量。

请注意 ,字符串包含在反引号 “ 中,而不是单引号中。

美元符号和花括号语法允许我们使用被评估的占位符。

<div className={`text-white ${myClass}`}>Some content here</div>

<div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}>
  Some content here
</div>

我们将模板文字包裹在其中的花括号标记了必须计算的表达式的开头。

打开右花括号之间的代码只是 JavaScript,因此我们在模板文字中使用的任何变量或表达式都将被评估。

当我们我们在 JSX 代码中呈现变量或表达式时,必须将其包裹在花括号中。

<h2>Hello {name}</h2>

我们还可以在 JSX 代码之外使用模板文字。

const num = 50;

const result = `${num + 50} percent`;

console.log(result); // 👉️ 100 percent

默认情况下,模板文字将部分连接成一个字符串。

我们还可以使用模板文字在多行字符串中插入变量。

const color1 = 'red';
const color2 = 'blue';

const poem = `roses are ${color1}
violets are ${color2}`;

console.log(poem);
// 👉️ roses are red
// 👉️ violets are blue

这非常有用,因为我们不必在每一行上添加换行符,而不是在连接字符串时。

我们甚至可以在模板文字中调用函数。

import './App.css';

export default function App() {
  const subtract = (a, b) => {
    return a - b;
  };

  const myClass = 'bg-salmon';

  const num = 30;
  return (
    <div>
      <div
        style={{fontSize: `${subtract(60, 20)}px`}}
        className={`padding-${subtract(100, 80)} text-white ${myClass}`}
      >
        Some content here
      </div>
    </div>
  );
}

这是一个将三元运算符与模板文字一起使用的示例。

const color1 = 'blue';
const color2 = 'red';

const result = `${color1.length > color2.length ? color1 : color2}`;

console.log(result); // 👉️ blue

三元运算符基本上是一个 if/else 语句。 问号之前的部分被评估,如果它返回一个真值,则运算符返回冒号之前的值,否则返回冒号之后的值。

import './App.css';

export default function App() {
  return (
    <div>
      <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}>
        Some content here
      </div>
    </div>
  );
}

示例中的三元运算符检查字符串 hi 的长度是否等于 2,如果是,则返回字符串 bg-salmon,否则返回空字符串。

我们还可以在模板文字中使用逻辑 OR || 和逻辑 AND && 运算符。

const num1 = 0;
const num2 = 100;

const result = `${num1 || num2}`;
console.log(result); // 👉️ 100

逻辑或 || 运算符如果为真则将值返回到左侧,否则将值返回到右侧。

下面是一个将逻辑 AND && 运算符与模板文字一起使用的示例。

const bool = true;
const str = 'hello';

const result = `${bool && str}`;
console.log(result); // 👉️ hello

逻辑与 && 运算符如果为假则将值返回到左侧,否则将值返回到右侧。