JSX (React Variable Statements)로 HTML 삽입
JSX에서 React Variables가있는 HTML을 삽입 해야하는 React로 무언가를 만들고 있습니다. 다음과 같은 변수를 갖는 방법이 있습니까?
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
이렇게 반응에 삽입하고 작동합니까?
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
예상대로 HTML을 삽입 했습니까? 나는이 인라인을 수행 할 수있는 반응 함수 또는 이것이 작동 할 수있는 것들을 파싱하는 방법에 대해 아무것도 보거나 듣지 못했습니다.
당신이 사용할 수있는 dangerouslySetInnerHTML를 , 예를 들어,
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
);
}
주 dangerouslySetInnerHTML
당신이 주입 된 HTML 문자열이 무엇인지 모르는 경우 위험 할 수 있습니다. 스크립트 태그를 통해 악의적 인 클라이언트 측 코드를 삽입 할 수 있기 때문입니다.
렌더링하는 HTML이 XSS (Cross-Site Scripting) 안전하다는 것을 100 % 확신 할 수 없다면 DOMPurify 와 같은 유틸리티를 통해 HTML 문자열을 삭제하는 것이 좋습니다 .
예:
import DOMPurify from 'dompurify'
const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
);
}
risklySetInnerHTML 은 태그 내부에 설정되어 있기 때문에 많은 단점이 있습니다.
이 목적으로 npm에서 찾은 것처럼 반응 래퍼를 사용하는 것이 좋습니다. html-react-parser 도 같은 작업을 수행합니다.
import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content">{Parser(thisIsMyCopy)}</div>
);
}
매우 간단한 :)
를 사용하여 ''
문자열로 만듭니다. 쉼표를 거꾸로 사용하지 않으면 정상적으로 작동합니다.
린터 오류를 피하기 위해 다음과 같이 사용합니다.
render() {
const props = {
dangerouslySetInnerHTML: { __html: '<br/>' },
};
return (
<div {...props}></div>
);
}
import { Fragment } from 'react' // react version > 16.0
var thisIsMyCopy = (
<Fragment>
<p>copy copy copy
<strong>strong copy</strong>
</p>
</Fragment>
)
''을 사용하면 값이 문자열로 설정되고 React는 그것이 HTML 요소인지 알 방법이 없습니다. React에 HTML 요소임을 알리기 위해 다음을 수행 할 수 있습니다.
- Remove the
''
and it would work - Use
<Fragment>
to return a HTML element.
If anyone else still lands here. With ES6 you can create your html variable like so:
render(){
var thisIsMyCopy = (
<p>copy copy copy <strong>strong copy</strong></p>
);
return(
<div>
{thisIsMyCopy}
</div>
)
}
You can also include this HTML in ReactDOM like this:
var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);
ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));
Here are two links link and link2 from React documentation which could be helpful.
참고URL : https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx
'Programing' 카테고리의 다른 글
글꼴 크기 macvim을 변경 하시겠습니까? (0) | 2020.05.24 |
---|---|
단위 테스트 내부에서 코드가 번들 자원을 찾을 수없는 이유는 무엇입니까? (0) | 2020.05.24 |
잘못된 문자열 오프셋 경고 PHP (0) | 2020.05.24 |
응용 프로그램 자동 빌드 버전 관리 (0) | 2020.05.24 |
NSUserDefaults에 NSDate를 저장하는 가장 좋은 방법은 무엇입니까? (0) | 2020.05.24 |