React-소품에서 HTML 태그를 전달하는 방법?
다음과 같이 HTML 태그로 텍스트를 전달할 수 있기를 원합니다.
<MyComponent text="This is <strong>not</strong> working." />
그러나 MyComponent
의 렌더링 메서드 내부에서 인쇄 this.props.text
하면 문자 그대로 모든 것이 인쇄됩니다.
This is <strong>not</strong> working.
React가 HTML을 구문 분석하고 올바르게 덤프하는 방법이 있습니까?
문자열 및 JSX 요소와 함께 혼합 배열을 사용할 수 있습니다 ( 여기 문서 참조 ).
<MyComponent text={["This is ", <strong>not</strong>, "working."]} />
작동하는 것을 보여주는 바이올린이 있습니다 : http://jsfiddle.net/7s7dee6L/
또한 마지막 수단으로 항상 원시 HTML을 삽입 할 수 있지만 속성 값을 삭제하지 않으면 XSS (교차 사이트 스크립팅) 공격에 노출 될 수 있으므로주의해야합니다.
실제로 여러 가지 방법이 있습니다.
소품 내부에서 JSX를 사용하고 싶습니다.
{}를 사용하여 JSX가 매개 변수를 구문 분석하도록 할 수 있습니다. 유일한 제한은 모든 JSX 요소와 동일합니다. 하나의 루트 요소 만 반환해야합니다.
myProp={<div><SomeComponent>Some String</div>}
이를위한 가장 읽기 쉬운 방법은 JSX 구성 요소를 반환 할 함수 renderMyProp (표준 렌더링 함수와 마찬가지로)를 만든 다음 myProp = {this.renderMyProp ()}를 호출하는 것입니다.
HTML 만 문자열로 전달하려고합니다.
기본적으로 JSX에서는 문자열 값에서 원시 HTML을 렌더링 할 수 없습니다. 그러나 그렇게하는 방법이 있습니다.
myProp="<div>This is some html</div>"
그런 다음 구성 요소에서 다음과 같이 사용할 수 있습니다.
<div dangerouslySetInnerHTML=myProp={{ __html: this.renderMyProp() }}></div>
이 솔루션은 사이트 간 스크립팅 위조 공격에 대해 '열릴 수 있습니다'. 또한 간단한 HTML 만 렌더링 할 수 있으며 JSX 태그 나 구성 요소 또는 기타 멋진 것을 렌더링 할 수 없습니다.
배열 방법
반응에서 JSX 요소의 배열을 전달할 수 있습니다. 그것의 의미는:
myProp={["This is html", <span>Some other</span>, "and again some other"]}
다음과 같은 이유로이 방법을 권장하지 않습니다.
- 경고 (누락 된 키)가 생성됩니다.
- 읽을 수 없습니다
- 실제로 JSX 방식이 아니라 의도 된 디자인보다 해킹에 가깝습니다.
아이들 방법
완전성을 위해 추가하지만 이에 대응하여 구성 요소 '내부'인 모든 하위 항목을 가져올 수도 있습니다.
따라서 다음 코드를 사용하면 :
<SomeComponent>
<div>Some content</div>
<div>Some content</div>
</SomeComponent>
그러면 두 div가 SomeComponent에서 this.props.children으로 사용 가능하며 표준 {} 구문으로 렌더링 될 수 있습니다.
이 솔루션은 구성 요소에 전달할 HTML 콘텐츠가 하나만있을 때 완벽합니다 (Popin의 콘텐츠 만 자식으로 사용하는 Popin 구성 요소를 상상해보십시오).
그러나 콘텐츠가 여러 개인 경우 자녀를 사용할 수 없거나 적어도 여기에서 다른 솔루션과 결합해야합니다.
위험하게 사용할 수 있습니다 .SetInnerHTML
html을 일반 문자열로 보내십시오.
<MyComponent text="This is <strong>not</strong> working." />
그리고 다음과 같이 JSX 코드에서 렌더링합니다.
<h2 className="header-title-right wow fadeInRight"
dangerouslySetInnerHTML={{__html: props.text}} />
사용자가 입력 한 데이터를 렌더링하는 경우주의하십시오. XSS 공격의 피해자가 될 수 있습니다
문서는 다음과 같습니다 : https://facebook.github.io/react/tips/dangerously-set-inner-html.html
나를 위해 그것은 소품 어린이에 html 태그를 전달하여 작동했습니다.
<MyComponent>This is <strong>not</strong> working.</MyComponent>
var MyComponent = React.createClass({
render: function() {
return (
<div>this.props.children</div>
);
},
클라이언트 측 반응 애플리케이션에서 일부 html이있는 문자열로 소품을 렌더링하는 몇 가지 방법이 있습니다. 하나는 다른 것보다 더 안전합니다 ...
1-소품을 jsx로 정의 (내 기본 설정)
const someProps = {
greeting: {<div>Hello<a href="/${name_profile}">${name_profile}</a></div>}
}
const GreetingComopnent = props => (
<p>{props.someProps.greeting}</p>
)
• 여기서 유일한 요구 사항은이 prop을 생성하는 파일이 무엇이든 React를 종속성으로 포함해야한다는 것입니다 (헬퍼 파일 등에서 prop의 jsx를 생성하는 경우).
2-innerHtml을 위험하게 설정
const someProps = {
greeting: '<React.Fragment>Hello<a href="/${name_profile}">${name_profile}</a></React.Fragment>'
}
const GreetingComponent = props => {
const innerHtml = { __html: props.someProps.greeting }
return <p dangerouslySetInnerHtml={innerHtml}></p>
}
• This second approach is discouraged. Imagine an input field whose input value is rendered as a prop in this component. A user could enter a script tag in the input and the component that renders this input would execute this potentially malicious code. As such, this approach has the potential to introduce cross-site scripting vulnerabilities. For more information, refer to the official React docs
<MyComponent text={<span>This is <strong>not</strong> working.</span>} />
and then in your component you can do prop checking like so:
import React from 'react';
export default class MyComponent extends React.Component {
static get propTypes() {
return {
text: React.PropTypes.object, // if you always want react components
text: React.PropTypes.any, // if you want both text or react components
}
}
}
Make sure you choose only one prop type.
From React v16.02 you can use a Fragment.
<MyComponent text={<Fragment>This is an <strong>HTML</strong> string.</Fragment>} />
More info: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
You can do it in 2 ways that I am aware of.
1- <MyComponent text={<p>This is <strong>not</strong> working.</p>} />
And then do this
class MyComponent extends React.Component {
render () {
return (<div>{this.props.text}</div>)
}
}
Or second approach do it like this
2- <MyComponent><p>This is <strong>not</strong> working.</p><MyComponent/>
And then do this
class MyComponent extends React.Component {
render () {
return (<div>{this.props.children}</div>)
}
}
In my project I had to pass dynamic html snippet from variable and render it inside component. So i did the following.
defaultSelection : {
innerHtml: {__html: '<strong>some text</strong>'}
}
defaultSelection object is passed to component from .js
file
<HtmlSnippet innerHtml={defaultSelection.innerHtml} />
HtmlSnippet component
var HtmlSnippet = React.createClass({
render: function() {
return (
<span dangerouslySetInnerHTML={this.props.innerHtml}></span>
);
}
});
react doc for dangerouslySetInnerHTML
You could also use a function on the component to pass along jsx to through props. like:
var MyComponent = React.createClass({
render: function() {
return (
<OtherComponent
body={this.body}
/>
);
},
body() {
return(
<p>This is <strong>now</strong> working.<p>
);
}
});
var OtherComponent = React.createClass({
propTypes: {
body: React.PropTypes.func
},
render: function() {
return (
<section>
{this.props.body()}
</section>
);
},
});
@matagus answer is fine for me, Hope below snippet is helped those who wish to use a variable inside.
const myVar = 'not';
<MyComponent text={["This is ", <strong>{`${myVar}`}</strong>, "working."]} />
Yes, you can it by using mix array with strings and JSX elements. reference
<MyComponent text={["This is ", <strong>not</strong>, "working."]} />
Is there a reason no one has suggested react-html-parser? It seems like a good way to work with imported HTML without having to do it dangerously
https://www.npmjs.com/package/react-html-parser
Parser from html-react-parser is a good solution. You just have to
- install it with npm or yarn
- import Parser from 'html-react-parser';
call it with :
<MyComponent text=Parser("This is <strong>not</strong> working.") />
and it works well.
Adding to the answer: If you intend to parse and you are already in JSX but have an object with nested properties, a very elegant way is to use parentheses in order to force JSX parsing:
const TestPage = () => (
<Fragment>
<MyComponent property={
{
html: (
<p>This is a <a href='#'>test</a> text!</p>
)
}}>
</MyComponent>
</Fragment>
);
Have appended the html in componentDidMount using jQuery append. This should solve the problem.
var MyComponent = React.createClass({
render: function() {
return (
<div>
</div>
);
},
componentDidMount() {
$(ReactDOM.findDOMNode(this)).append(this.props.text);
}
});
참고URL : https://stackoverflow.com/questions/33381029/react-how-to-pass-html-tags-in-props
'IT story' 카테고리의 다른 글
Web API 2 : 객체 및 해당 하위 객체에서 camelCased 속성 이름과 함께 JSON을 반환하는 방법 (0) | 2020.08.29 |
---|---|
문자열에서 json 객체 android로 변환 (0) | 2020.08.29 |
PHP : 처리 방법 (0) | 2020.08.29 |
R 스크립트에서 직접 Excel 파일 읽기 (0) | 2020.08.29 |
C # http 웹 GET 요청을 올바르게 만드는 방법 (0) | 2020.08.29 |