javascript - 通过 props 传递字符串并使用 const 值时的不同输出

标签 javascript css reactjs

我想使用 props 将文本传递到我的 React 组件。重要的是我需要换行符号 ("\n") 才能工作。

我的例子很简单:

class UnderlinedText extends React.Component {
  render() {
    const text = 'Hello\n this is a test'; // this works
    // const text = this.props.text; this does NOT work
    return (
      <div className="textContainer">{text}</div>
    );
  }
}

ReactDOM.render(
  <UnderlinedText />,
  document.getElementById("root")
);
.textContainer {
  white-space: pre-line;
}
<div id="root"></div>

<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>

使用上面的硬编码文本一切正常(即使在调试中我也看到字符串跨越多行)。但是通过像这样的 Prop 使用它:

class UnderlinedText extends React.Component {
  render() {
    const text = this.props.text;
    return (
      <div className="textContainer">{text}</div>
    );
  }
}

ReactDOM.render(
  <UnderlinedText text='Hello\n this is a test' />,
  document.getElementById("root")
);
.textContainer {
  white-space: pre-line;
}
<div id="root"></div>

<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>

不创建新行并且调试中的字符串包含所有新行符号(“\n”)。

这两种解决方案之间的区别在哪里?以及如何解决?

最佳答案

因为你在中使用了文字字符串

<UnderlinedText text='Hello\n this is a test' />

React 将其视为文字文本\n\n,就像在 HTML 属性中一样。

如果您想提供其中包含 JavaScript 转义序列的 JavaScript 字符串,请在其周围使用 {} 以切换到 JavaScript 表达式上下文:

<UnderlinedText text={'Hello\n this is a test'} />

实例:

class UnderlinedText extends React.Component {
  render() {
    const text = this.props.text;
    return (
      <div className="textContainer">{text}</div>
    );
  }
}

ReactDOM.render(
  <UnderlinedText text={'Hello\n this is a test'} />,
  document.getElementById("root")
);
.textContainer {
  white-space: pre-line;
}
<div id="root"></div>

<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>

关于javascript - 通过 props 传递字符串并使用 const 值时的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53971297/

相关文章:

javascript - 如何在 Paint Worklet 中导入/使用库?

jQuery 隐藏和显示带有指示器的 div

javascript - React js日期选择器的多个实例

javascript - JS/jquery : how would I iterate through each image in my HTML?

javascript - 如何根据时隙将对象时间序列数组拆分为多个时间序列?

java - 如何通过 header 中的自定义参数通过 RestTemplate 发送 POST 请求

javascript - React hook 使用类对象作为 useState

javascript - 使用 jquery 和 javascript 遍历 dom 的正确方法以及 "this"的用法

css - Bootstrap 4 alpha 6 - 行内卡片行为

javascript - 在提交表单之前,所需的文本区域以红色突出显示