我需要在句子之间添加分隔符,但是当我这样做时,我得到了[object Object]来代替换行符。有人可以告诉我如何解决此问题吗?
const openingText = 'We\'re happy to hear your project is underway. '
+ <br /> + 'You can review this business to tell others about your experience.';
浏览器中的示例:
开发工具示例:
当我这样写时,出现语法错误:
const openingText = (
<>
We're happy to hear your project is underway.
<br /><br />
You can review this business to tell others about your experience.
</>
);
当我在引号中添加br标签时,它只是认为它是常规文本:
const openingText = 'We\'re happy to hear your project is underway. <br /><br />' +
'You can review this business to tell others about your experience.';
答案 0 :(得分:2)
因为您无法添加string
和Object
:
var tmp = {}
console.log('This is an object: ' + tmp)
您想对React进行以下操作:
const openingText = (
<>
We're happy to hear your project is underway.
<br />
You can review this business to tell others about your experience.
</>
);
如果使用该语法出错,则可能是您使用的是较早版本的react或不支持React Fragment short syntax的工具,在这种情况下,您应该可以这样做:
const openingText = (
<React.Fragment>
We're happy to hear your project is underway.
<br />
You can review this business to tell others about your experience.
</React.Fragment>
);
答案 1 :(得分:0)
您必须使用:dangerouslysetinnerhtml
class App extends React.Component {
render() {
const str = 'We\'re happy to hear your project is underway.<br />You can review this business to tell others about your experience.';
return (
<div dangerouslySetInnerHTML = {{__html: str}} >
</div>
)
}
}
ReactDOM.render( < App / > , document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
或使用模板文字:
class App extends React.Component {
render() {
const str = `We're happy to hear your project is underway.
You can review this business to tell others about your experience.`;
return (
<div style = {{ whiteSpace: 'pre-line'}} >
{str}
</div>
)
}
}
ReactDOM.render( < App / > , document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>