javascript - 试图在 react 中的文本之间添加 br 标签

标签 javascript jquery html reactjs redux

我正在尝试在 react 文本之间添加 br 标签。 你们能告诉我如何添加它吗? 我尝试添加 br 标签......但是如果我添加我在浏览器中得到
标签。 在下面提供我的代码。 你们能告诉我如何解决吗?

let sportsDescription = '';

        if(sportsInfo !== '' && !isSportsSetupActive) {
            sportsDescription = 'testing <br /> testing';

        }else if(isSportsSetupActive) {
            sportsDescription = 'testing <br /> testing';

        }



        return (
            <div id="main" className="section flex-container flex-full">
                <section className="page-content flex-item">
                    <section className="gray-box">
                        <h2>Welcome to your  dashboard{formatName}.</h2>
                        <p className="ft-intro ft-day1 ft-day2">{sportsDescription}</p>

                    </section>
                </section>
            </div>
    );

最佳答案

来自ReactJS Docs ...

In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.

在您的示例中,{sportsDescription}被解释为一个字符串。 React 不会将该变量中的任何内容视为 DOM 元素。这就是为什么你的 <br/>仅呈现为字符串。

或者,您可以这样做(但这通常是个坏主意)...

 <p 
   className="ft-intro ft-day1 ft-day2" 
   dangerouslySetInnerHTML={{__html:sportsDescription}} 
 />

这样,React 就正确地识别了您将 HTML 包含在字符串 sportsDescription 中的意图。并呈现所需的 <br/>元素。

这是一篇文章的引述,该文章更详细地介绍了 Getting Started with ReactJS :

The React module has a createClass method that takes an object as its only parameter. We define only one key to start with: render. The value of render is a function that returns a virtual DOM element. One of the keys to React’s performance is its virtual DOM abstraction. Essentially, it’s a difference engine that calculates the difference between the existing DOM and the DOM that is to be rendered and only modifies the necessary elements and attributes. Inside the render function, you may have noticed that I included HTML markup. That’s JSX. It won’t pass validation as legal Javascript. Instead, it requires the Babel transpiler.

关于javascript - 试图在 react 中的文本之间添加 br 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878925/

相关文章:

javascript - 样式组件缺少 className

jquery - Google Analytics 事件跟踪问题

javascript - .data() 没有按预期工作

html - <p> 标签是 XHTML 中的 block 级元素?

cURL 请求的 Javascript 等效项

javascript - Python3请求库提交不允许post请求的表单

html - 删除加载页面上的一些 <div>

python - 如何从txt文件中删除奇怪的编码

javascript - 访问嵌套对象

javascript - Jquery - 使用谷歌字体链接重新加载 css