programing

리액트를 사용하여 html 엔티티를 표시하는 방법

goodjava 2023. 4. 5. 21:48

리액트를 사용하여 html 엔티티를 표시하는 방법

cubic html 엔티티(superscript 3)를 표시하고 싶습니다.이렇게 하고 있습니다.

const formatArea = function(val){
    return val + " ft³";
}

어디에formatArea컴포넌트 내부에서 호출되고 있습니다.'

render(){
    return (
        <div>
            {formatArea(this.props.area)}
        </div>
    );
}

하지만 브라우저에는 다음과 같이 표시됩니다.ft&sup3;

다른 옵션은 CharCode 메서드에서 사용하는 것입니다.

const formatArea = (val) => {
    return val + ' ft' + String.fromCharCode(179);
}

React fragment를 사용한 새로운 방법:

<>&sup3;</>

고객의 경우는, 다음과 같습니다.

const formatArea = function(val){
    return <>{val + ' '}&sup3;</>
}

JSX를 사용하여 다음과 같이 검색:

const formatArea = (val) => {
    return (<span>{val}&nbsp;ft<sup>3</sup></span>);
}

다음 방법으로 얻을 수 있습니다.dangerouslySetInnerHTMLjsx의 기능.

또 다른 방법은 use consport입니다.unicodehtml 엔티티의 문자이며 일반 문자열로 사용합니다.

const formatArea = function(val){
    return val + " ft&sup3;";
}

const Comp = ({text}) => (
<div>
<div dangerouslySetInnerHTML={{__html: `${text}`}} />
<div>{'53 ft\u00B3'}</div>
</div>

);

ReactDOM.render( <Comp text={formatArea(53)} /> ,
  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

    const formatArea = val => <div>{val} ft{'³'}</div>

  • 방법 2

    const formatArea = val => <div>{val} ft{'\u00B3'}</div>

  • 방법 3: CharCode에서

    const formatArea = val => <div>{val} ft{String.fromCharCode(parseInt('B3', 16))}</div>

  • 방법 4

    const formatArea = val => <div>{val} ft{String.fromCharCode(179)}</div>

  • 방법 5: HTML 코드

    const formatArea = val => <div>{val} ft&sup3;</div>

  • 방법 6

    const formatArea = val => <div>{val} ft&#179;</div>

  • 방법 7

    const formatArea = val => <div>{val} ft<sup>3</sup></div>

그런 다음 렌더링할 수 있습니다.

render() {
  return (
    {formatArea(this.props.area)}
  )
}
const formatArea = function(val){
  return <>{val} ft<span>&sup3;</span></>;
}

render(){
    return (
        <div>
            {formatArea(this.props.area)}
        </div>
    );
}

데모

언급URL : https://stackoverflow.com/questions/44116800/how-to-show-html-entity-using-react