我想我是老式的并且构建 HTML 和数据字符串。当我返回字符串时,期望 React 能够很好地处理这个问题。有没有明显的方法?和<br>
似乎没有任何地方工作。有替代品吗?
(如下:剪切并粘贴到 .html 文件中,它将运行。)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root"></div>
<script type="text/babel">
var SportsPeople = [
{thegame: 'Football', name: 'Tom Brady' },
{thegame: 'Basketball', name: 'Le Bron James' }
]
class Banner extends React.Component {
constructor(props) { super(props); };
render() { return ( <div>Big Banner on the Top</div>); }
}
class AnotherLine extends React.Component {
constructor(props) { super(props); };
render() {
let htmlStuff = "";
let workTable = this.props.stars;
for (let i = 0; i < workTable.length; i++)
{
htmlStuff += workTable[i].thegame;
htmlStuff += "<p> - </p>";
htmlStuff += workTable[i].name;
htmlStuff += "<br>";
}
console.log ( { htmlStuff } );
return ( <div> { htmlStuff } </div> );
} // End render
} // End CLASS
//==============================
class Main extends React.Component {
constructor(props) { super(props); };
render() {
return (
<div>
<Banner />
<AnotherLine
stars = { SportsPeople }
/>
</div>);
}
}
// =========================================
ReactDOM.render(
<Main />,
document.getElementById('root')
);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.38/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
</body>
</html>
最佳答案
也许尝试在 AnotherLine 组件中使用angerouslySetInnerHtml 属性,如下所示:
return (<div dangerouslySetInnerHTML={{__html:htmlStuff}}</div>)
请参阅此处的文档以获得更好的解释: https://facebook.github.io/react/docs/dom-elements.html
关于javascript - React - 如何返回 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268825/