呈现JavaScript时,为什么<br/>标签显示为[object Object]?

时间:2019-02-28 21:31:55

标签: javascript html reactjs

我需要在句子之间添加分隔符,但是当我这样做时,我得到了[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.';

浏览器中的示例:

enter image description here

开发工具示例:

enter image description here

当我这样写时,出现语法错误:

const openingText = (
  <>
      We're happy to hear your project is underway.
      <br /><br />
      You can review this business to tell others about your experience.
  </>
);

enter image description here

当我在引号中添加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.';

enter image description here

2 个答案:

答案 0 :(得分:2)

因为您无法添加stringObject

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>