我有一个服务器响应,其中包含一个html字符串,该字符串作为prop传递给react组件。在html中,有些代码需要用React组件替换。
我已经使用react-string-replace来使其工作,但它似乎不适用于HTML,因为标签被React转义。有谁知道如何解决这个问题?
import React from 'react';
import replace from 'react-string-replace';
const reg = /\{(name)\}/g;
const Name = props => {
return (
<div>Hello {props.name}</div>
)
}
class Embed extends React.Component {
render() {
const person = this.props.person
const component = <Name name={person.name} key={person.id} />;
const output = replace(
this.props.content,
reg,
prop => component
);
return (
<div>{output}</div>
)
}
}
const Greeting = props => {
return <Embed content="<div><h1>Greetings</h1> <strong>{name}</strong></div>" person={{ name: 'John', id: 123 }} />;
};
export default Greeting;
答案 0 :(得分:0)
试试这个 -
class Embed extends React.Component {
render() {
const person = this.props.person
const component = <Name name={person.name} key={person.id} />;
const output = replace(
this.props.content,
reg,
prop => component
);
return (
<div dangerouslySetInnerHTML={{ __html: output }}></div>
)
}
}
我建议更好的方法,如下所示 -
const reg = /\{(name)\}/g;
const Name = props => {
return (
<div>Hello {props.name}</div>
)
}
class Embed extends React.Component {
render() {
const person = this.props.person;
const component = <Name name={person.name} key={person.id} />;
return (
<div><h1>Greetings</h1> <strong>{component}</strong></div>
);
}
}
const Greeting = props => {
return (<Embed person={{ name: 'John', id: 123 }} >
</Embed>);
};
ReactDOM.render(
<Greeting/>,
document.getElementById('test')
);
<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="test">
</div>
答案 1 :(得分:0)
想要提醒你:
dangerouslySetInnerHTML是React替代使用innerHTML的替代品 浏览器DOM。通常,从代码设置HTML是有风险的,因为 很容易无意中将您的用户暴露给跨站点脚本 (XSS)攻击。因此,您可以直接从React设置HTML,但您有 输入dangerouslySetInnerHTML并传递一个带有__html的对象 关键,提醒自己这很危险。
试试这个:
const Name = props => {
return (
<div>
Hello {props.name}
</div>
)
}
class Embed extends React.Component {
render() {
let content = this.props.content.replace('{name}', this.props.person.name);
return (
<div>
<Name person={this.props.person}/>
<div dangerouslySetInnerHTML={{ __html: content}}></div>
</div>
)
}
}
const Greeting = props => {
return <Embed content="<div><h1>Greetings</h1> <strong>{name}</strong></div>" person={{ name: 'John', id: 123 }} />;
};
ReactDOM.render(<Greeting />, document.getElementById('container'));
查看jsfiddle
上的工作示例:https://jsfiddle.net/h81q9nqd/