在 React 的模板文字中插入 html 标签

Iva*_*ana 10 javascript reactjs template-literals

我在 React 中有带有模板文字的变量:

const weatherForecast = `
  Today in <strong>${this.state.cityName}</strong>
  weather will be with <strong>${today.weather_state_name}</strong>,
  min temperature <strong>${parseInt(today.min_temp)}°C</strong>,
  max temperature <strong>${parseInt(today.max_temp)}°C</strong>,
  and humidity will be <strong>${today.humidity}%</strong>
`;
Run Code Online (Sandbox Code Playgroud)

我想在其中插入 HTML 代码,如您所见,这是 tag 。这可能吗,我该怎么做。我用谷歌搜索,但我找不到答案。

Pri*_*Das 15

const weatherForecast = 
`Today in <strong>${this.state.cityName}</strong> weather will be with <strong>${today.weather_state_name}</strong>, min temperature <strong>${parseInt(today.min_temp)}°C</strong>, max temperature <strong>${parseInt(today.max_temp)}°C</strong>, and humidity will be <strong>${today.humidity}%</strong>`;
Run Code Online (Sandbox Code Playgroud)

React 会将其视为字符串而不是 jsx。你可以做的是

const weatherForecast = 
`Today in <strong>${this.state.cityName}</strong> weather will be with <strong>${today.weather_state_name}</strong>, min temperature <strong>${parseInt(today.min_temp)}°C</strong>, max temperature <strong>${parseInt(today.max_temp)}°C</strong>, and humidity will be <strong>${today.humidity}%</strong>`;
Run Code Online (Sandbox Code Playgroud)

然后render像这样在你的方法中渲染它

const weatherForecast = 
<p>Today in <strong>{this.state.cityName}</strong> weather will be with <strong>{today.weather_state_name}</strong>, min temperature <strong>{parseInt(today.min_temp)}°C</strong>, max temperature <strong>{parseInt(today.max_temp)}°C</strong>, and humidity will be <strong>{today.humidity}%</strong></p>;

Run Code Online (Sandbox Code Playgroud)

  • @Ivana,但为什么呢?JSX 允许您使用条件,无论您要插入元素还是纯字符串 (2认同)