最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React rendering variable with html characters escaped - Stack Overflow

programmeradmin1浏览0评论

I am learning React and have run into the following situation:

I have a string variable that I am passing as a prop to different ponents to be rendered by JSX.

When the ponent and its sub-ponents are rendered, the string does not render html special characters, instead rendering the character code as text.

How can I get the variable to render as html?

Here is the code for a ponent that works pletely, except that the tempUnitString variable renders as &deg; K, while the <th> below renders its units as ° K.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../ponents/chart';
import GoogleMap from '../ponents/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 = "&deg; " + 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);

UPDATE

Using the documentation passed to me by @James Ganong I set up a boolean prop on the subponent isTemp and based on that created a JSX variable.

The subponent (minus includes and func definitions) looks like this:

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>
  );
}

The call to it looks like this:

<Chart color="red" data={ temp } units={ tempUnits } isTemp={ true } />

I am learning React and have run into the following situation:

I have a string variable that I am passing as a prop to different ponents to be rendered by JSX.

When the ponent and its sub-ponents are rendered, the string does not render html special characters, instead rendering the character code as text.

How can I get the variable to render as html?

Here is the code for a ponent that works pletely, except that the tempUnitString variable renders as &deg; K, while the <th> below renders its units as ° K.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../ponents/chart';
import GoogleMap from '../ponents/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 = "&deg; " + 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);

UPDATE

Using the documentation passed to me by @James Ganong I set up a boolean prop on the subponent isTemp and based on that created a JSX variable.

The subponent (minus includes and func definitions) looks like this:

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>
  );
}

The call to it looks like this:

<Chart color="red" data={ temp } units={ tempUnits } isTemp={ true } />

Share Improve this question edited Mar 14, 2017 at 18:57 Judd Franklin asked Mar 13, 2017 at 23:17 Judd FranklinJudd Franklin 5702 gold badges5 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

React actually has a page that addresses this and some other potential solutions (using unicode characters, saving the file as utf8, using dangerouslySetInnerHtml): jsx-gotchas


Another option is to create a simple, reusable Temp ponent that has types you pass it:

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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Without string concatenation html symbols works as usual. For some reason, when you concatenate a symbol with a string, then the symbol isn't decoded and it's rended as characters.

You can workaround it as in the example below or use a plugin (html-entities for instance).

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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>