program story

React 컴포넌트에서 HTML 문자열을 실제 HTML로 렌더링

inputbox 2020. 8. 27. 07:45
반응형

React 컴포넌트에서 HTML 문자열을 실제 HTML로 렌더링


내가 시도한 것과 그것이 어떻게 잘못되었는지는 다음과 같습니다.

이것은 작동합니다 :

<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />

이것은하지 않습니다 :

<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />

설명 속성은 HTML 콘텐츠의 일반적인 문자열입니다. 그러나 어떤 이유로 든 HTML이 아닌 문자열로 렌더링됩니다.

여기에 이미지 설명 입력

어떤 제안?


노드에 추가하려는 텍스트가 다음과 같이 이스케이프되지 않았는지 확인하십시오.

var prop = {
    match: {
        description: '&lt;h1&gt;Hi there!&lt;/h1&gt;'
    }
};

대신 :

var prop = {
    match: {
        description: '<h1>Hi there!</h1>'
    }
};

이스케이프되면 서버 측에서 변환해야합니다.

노드는 이스케이프되기 때문에 텍스트입니다.

노드는 이스케이프되기 때문에 텍스트입니다.

노드는 이스케이프되지 않기 때문에 dom 노드입니다.

노드는 이스케이프되지 않기 때문에 dom 노드입니다.


합니까는 this.props.match.description문자열 또는 객체인가? 문자열이면 HTML로 잘 변환되어야합니다. 예:

class App extends React.Component {

constructor() {
    super();
    this.state = {
      description: '<h1 style="color:red;">something</h1>'
    }
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.description }} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

결과 : http://codepen.io/ilanus/pen/QKgoLA?editors=1011

그러나 description: <h1 style="color:red;">something</h1>따옴표 없으면 다음 ''을 얻을 수 있습니다.

​Object {
$$typeof: [object Symbol] {},
  _owner: null,
  key: null,
  props: Object {
    children: "something",
    style: "color:red;"
  },
  ref: null,
  type: "h1"
}

If It's a string and you don't see any HTML markup the only problem i see is wrong markup..

UPDATE

If you are dealing with HTMLEntitles. You need to decode them before sending them to dangerouslySetInnerHTML that's why they called it dangerously :)

Working example:

class App extends React.Component {

  constructor() {
    super();
    this.state = {
      description: '&lt;p&gt;&lt;strong&gt;Our Opportunity:&lt;/strong&gt;&lt;/p&gt;'
    }
  }

   htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

I used 'react-html-parser'

yarn add react-html-parser
import ReactHtmlParser from 'react-html-parser'; 

<div> { ReactHtmlParser (html_string) } </div>

Source on npmjs.com


If you have control over where the string containing html is coming from (ie. somewhere in your app), you can benefit from the new <Fragment> API, doing something like:

import React, {Fragment} from 'react'

const stringsSomeWithHtml = {
  testOne: (
    <Fragment>
      Some text <strong>wrapped with strong</strong>
    </Fragment>
  ),
  testTwo: `This is just a plain string, but it'll print fine too`,
}

...

render() {
  return <div>{stringsSomeWithHtml[prop.key]}</div>
}

If you have control to the {this.props.match.description} and if you are using JSX. I would recommend not to use "dangerouslySetInnerHTML".

// In JSX, you can define a html object rather than a string to contain raw HTML
let description = <h1>Hi there!</h1>;

// Here is how you print
return (
    {description}
);

참고URL : https://stackoverflow.com/questions/39758136/render-html-string-as-real-html-in-a-react-component

반응형