여기 내가 시도한 것과 그것이 어떻게 잘못되었는지가 있습니다.
이것은 작동합니다 :
<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />
이것은하지 않습니다 :
<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />
description 속성은 일반적인 HTML 콘텐츠 문자열입니다. 그러나 어떤 이유로 HTML이 아닌 문자열로 렌더링됩니다.
어떤 제안?
답변
노드에 추가하려는 텍스트가 다음과 같이 이스케이프되지 않았는지 확인하십시오.
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
이 대신에 :
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
이스케이프 된 경우 서버 측에서 변환해야합니다.
이스케이프 되었기 때문에 노드는 텍스트입니다.
이스케이프되지 않았기 때문에 노드는 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"
}
문자열이고 HTML 마크 업이 표시되지 않는 경우 내가 볼 수있는 유일한 문제는 잘못된 마크 업입니다 ..
최신 정보
HTMLEntitles를 다루는 경우. 보내기 전에 해독해야합니다dangerouslySetInnerHTML
하므로 그것이 위험하다고 불렀습니다. 🙂
작업 예 :
class App extends React.Component {
constructor() {
super();
this.state = {
description: '<p><strong>Our Opportunity:</strong></p>'
}
}
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'));
답변
‘react-html-parser’를 사용합니다.
yarn add react-html-parser
import ReactHtmlParser from 'react-html-parser';
<div> { ReactHtmlParser (html_string) } </div>
npmjs.com의 소스
더 많은 가시성을 위해 @okram의 의견을 높이십시오.
github 설명에서 : npmjs.com에서 risklySetInnerHTML을 사용하지 않아도 HTML 문자열을 React 구성 요소로 직접 변환 HTML 문자열을 React 구성 요소로 변환하는 유틸리티. dangerouslySetInnerHTML의 사용을 피하고 표준 HTML 요소, 속성 및 인라인 스타일을 React와 동등한 것으로 변환합니다.
답변
html을 포함하는 문자열이 어디에서 왔는지 (예 : 앱의 어딘가) 제어 할 수 있다면 새로운 기능을 활용할 수 있습니다 <Fragment>
다음과 같이 API를 .
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>
}
답변
당신은 React의 dangerouslySetInnerHTML 메소드를 사용합니다.
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
또는 다음과 같은 쉬운 방법으로 더 많은 것을 구현할 수 있습니다. React 앱에서 HTML 원시 렌더링
답변
dangerouslySetInnerHTML
dangerouslySetInnerHTML은 브라우저 DOM에서 innerHTML을 사용하는 React의 대체품입니다. 일반적으로 코드에서 HTML을 설정하면 사용자가 실수로 XSS (Cross-Site Scripting) 공격에 노출되기 때문에 위험합니다. 따라서 React에서 직접 HTML을 설정할 수는 있지만, 위험하다는 것을 상기시키기 위해 dangerouslySetInnerHTML을 입력하고 __html 키로 객체를 전달해야합니다. 예를 들면 다음과 같습니다.
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
답변
span을 사용하여 innerHTML을 함께 사용합니다.
import React, { useRef, useEffect, useState } from 'react';
export default function Sample() {
const spanRef = useRef<HTMLSpanElement>(null);
const [someHTML,] = useState("some <b>bold</b>");
useEffect(() => {
if (spanRef.current) {
spanRef.current.innerHTML = someHTML;
}
}, [spanRef.current, someHTML]);
return <div>
my custom text follows<br />
<span ref={spanRef} />
</div>
}