为什么我的 <br /> 标签在呈现我的 javascript 时显示为 [object Object]?

IT技术 javascript html reactjs
2022-07-17 01:09:37

我需要在我的句子之间添加中断标签,但是当我这样做时,我会得到 [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.';

在此处输入图像描述

2个回答

因为您不能添加 astring和 an 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>
);

您必须使用:dangeroussetinnerhtml

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>