简体   繁体   中英

In React Bootstrap, I want to format my text with html but can't

In my app, I am constructing a string:

tempString += "\n<b>" + dResult[y].dp5 + "</b>";

I'm able to convert my \\n to a <p> using the split below, but how can I format my text with styles, such as the <b> :

  let newText = randString.split('\n').map((item, i) => {
    return <p key={i}>{item}</p>;
  });

On my screen, my output is: <b>Text</b> , instead of actually bolding the text.

To render to HTML, stick with JSX and passing around rendered components rather than strings. You can pass an Array as a child to a React component, so keep an Array of components rather than a string:

const tempComp = [];
tempComp.push(<b>{dResult[y].dp5}</b>);

and then render it is a child:

<>
  {tempComp}
</>

 // Example class component function BoldedComponent() { const strings = ['hello', 'world', 'john doe was here']; const tempComp = strings.map(item => (<b>{item}</b>)); const noBoldComp = strings.map(item => (<p>{item}</p>)); return ( <div> {tempComp} {noBoldComp} </div> ); } // Render it ReactDOM.render( <BoldedComponent />, document.getElementById("react") );
 <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="react"></div>

Why not constructing your tempString as an array of strings so you don't have to use split() method and can still achieve this?

const tempString = [];
...
tempString.push(dResult[y].dp5);
...
...
let newText = tempString.map((item, i) => {
  return <b key={i}>{item}</b>;
});

Or even better by constructing your tempString as an array of react components:

const tempComp= [];
...
tempComp.push(<b key={i}>{dResult[y].dp5}</b>);
...
...
<>
 {tempComp}
<>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM