我想使用 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/