【问题标题】:React rendering variable with html characters escaped使用转义的 html 字符反应渲染变量
【发布时间】:2017-08-04 03:34:02
【问题描述】:

我正在学习 React,遇到了以下情况:

我有一个字符串变量,我将其作为道具传递给 JSX 渲染的不同组件。

在渲染组件及其子组件时,字符串不渲染html特殊字符,而是将字符代码渲染为文本。

如何让变量呈现为 html?

这是一个完全工作的组件的代码,除了tempUnitString 变量呈现为° K,而下面的<th> 将其单位呈现为° K。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map'

class WeatherList extends Component {
  renderWeather(cityData, tempUnits){
    const name = cityData.city.name;
    const id = cityData.city.id;
    const humidity = cityData.list.map(weather => weather.main.humidity);
    const pressure = cityData.list.map(weather => weather.main.pressure);
    const { lon, lat } = cityData.city.coord;
    let temp = cityData.list.map(weather => weather.main.temp);
    if (tempUnits === "K"){
        temp = cityData.list.map(weather => weather.main.temp);
    } else if (tempUnits === "F"){
        temp = cityData.list.map(weather => weather.main.temp * 9/5 - 459.67);
    } else {
        temp = cityData.list.map(weather => weather.main.temp - 273.15);
    }
    let tempUnitString = "° " + tempUnits;

    return (
      <tr key={ id }>
        <td><GoogleMap lat={ lat } lon={ lon } /></td>
        <td>
          <Chart color="red" data={ temp } units={ tempUnitString } />
        </td>
        <td>
          <Chart color="green" data={ pressure } units=" hPa" />
        </td>
        <td>
          <Chart color="orange" data={ humidity } units="%" />
        </td>
      </tr>);
  }
  render() {
    const tempUnits = this.props.preferences.length > 0 ? this.props.preferences[0].tempUnits : "K";

    return (
      <table className="table table-hover">
        <thead>
          <tr>
            <th>City</th>
            <th>Temperature (&deg; { tempUnits })</th>
            <th>Pressure (hPa)</th>
            <th>Humidity (%)</th>
          </tr>
        </thead>
        <tbody>
          { this.props.weather.map( item => this.renderWeather(item,tempUnits) ) }
        </tbody>
      </table>
    );
  }


}

function mapStateToProps({ weather, preferences }){// { weather } is shorthand for passing state and { weather:state.weather } below
  return { weather, preferences }; // === { weather:weather }
}

export default connect(mapStateToProps)(WeatherList);

更新

使用@James Ganong 传递给我的文档,我在子组件isTemp 上设置了一个布尔属性,并在此基础上创建了一个 JSX 变量。

子组件(减去 include 和 func 定义)如下所示:

export default (props) => {
  let tempDeg = '';
  if (props.isTemp){
    tempDeg = <span>&deg;</span>;
  }
  return (
    <div>
      <Sparklines height={ 120 } width={ 100 } data={ props.data }>
        <SparklinesLine color={ props.color } />
        <SparklinesReferenceLine type="avg" />
      </Sparklines>
      <div>{ average(props.data)} { tempDeg }{ props.units }</div>
    </div>
  );
}

对它的调用如下所示:

&lt;Chart color="red" data={ temp } units={ tempUnits } isTemp={ true } /&gt;

【问题讨论】:

    标签: javascript reactjs ecmascript-6 jsx


    【解决方案1】:

    没有字符串连接的 html 符号照常工作。出于某种原因,当您将符号与字符串连接时,该符号不会被解码,而是被渲染为字符。

    您可以按照下面的示例解决它或使用插件(例如html-entities)。

    const App = () => <Child deg="&deg;" temp={25} />;
    const Child = ({deg, temp}) => <div>{temp} {deg}</div>;
    
    ReactDOM.render(<App />, document.getElementById('root'))
    <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>

    【讨论】:

    • 嗨乔丹,问题是我想将连接的字符串作为参数传递到一个单独的组件中。我宁愿不必将笨重的条件逻辑放入子组件中,或者创建单独的组件来处理这种情况。
    • 我检查了你的方法,问题似乎在于字符串传递给子组件的方式
    • 也许从字符串变量到 props 属性的转换会改变渲染行为?
    • 这里描述了正在发生的事情:reactjs.cn/react/docs/jsx-gotchas.html。感谢詹姆斯的回答。
    【解决方案2】:

    React 实际上有一个页面可以解决这个问题和其他一些潜在的解决方案(使用 unicode 字符,将文件保存为 utf8,使用 dangerouslySetInnerHtml):jsx-gotchas


    另一种选择是创建一个简单、可重用的 Temp 组件,该组件具有您传递的类型:

    const TEMP_C = 'C';
    const TEMP_K = 'K';
    
    const Temp = ({ children, unit }) => <span>{children}&deg;{unit}</span>;
    
    const App = () => (
      <div>
        <p>Temperature 1: <Temp unit={TEMP_K}>25</Temp></p>
        <p>Temperature 2: <Temp unit={TEMP_C}>25</Temp></p>
      </div>
    );
    
    ReactDOM.render(<App />, document.getElementById('root'))
    <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. 如果您需要将道具作为 true 传递(例如 isTemp={true}),您实际上不需要 ={true} 部分,只需将 isTemp 设置为属性(没有等号)它评估为真。 2.你可以将if语句合并到jsx中,而不需要使用tempDeg变量。即用{props.isTemp &amp;&amp; (&lt;span&gt;&amp;deg;&lt;/span&gt;)}替换{ tempDeg }
    • 也为此干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2020-03-14
    • 2019-01-07
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多