Display edited/styled text - react

為{幸葍}努か 提交于 2021-02-11 13:32:08

问题


I am building a web app for posting announcements. The user get to use a rich text editor, meaning he can make letters bold, underline them and so one. I am then saving this text with the description "content" in my mongodb database as a string. Every post has a title and a content. When i am displaying the post instead of showing "this text is strong" it is showing "< strong>this text is strong< /strong>". (added a space in < strong> cause it would make it strong otherwise. you get what i mean :P ) obviously this is not happening only in the strong case but with all the edits. for example in paragraphs its like this < p> paragraph < /p> and so on.

How can i display the content like its meant to be (styled) and not just as a string with no edits and style? Maybe it's the fact that i store it in my db as a string? but then what type should i store it as?

Posting images for reference


回答1:


Allowing this is pretty dangerious, to be honest - you have to be EXTREMELY careful on what you allow and how you are sanitizing input (not allowing script tags, etc..)..

I wouldn't recommend doing this...

The reason this happens is because React is sanitizing the input for you (essentially turning any html into just a plain string - not true sanitization but you get the point)... if you want to render user input HTML, you have to use dangerouslySetInnerHTML - it must be presented in the following format: { __html: '<p>The Dangerous HTML</p>' }

const { useState, dangerouslySetInnerHTML } = React;
const { render } = ReactDOM;

function App() {
  const [html, setHtml] = useState();
  
  const handleChange = event => {
    setHtml({ __html: event.target.value});
  }
  
  return (
    <div>
      <h3>Enter some html</h3>
      <input onChange={handleChange} type="text" /> 
      {html && <div dangerouslySetInnerHTML={html} />}
    </div>
  );
}

render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>


来源:https://stackoverflow.com/questions/60434984/display-edited-styled-text-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!