简体   繁体   English

反应:如何将 jsx 保存到 state 然后在 dom 中显示 jsx

[英]React: How to save jsx to state then show jsx in dom

Im trying to set the value of the variable showMe to some jsx and then save that in state.我试图将变量showMe的值设置为一些 jsx,然后将其保存在 state 中。

 const showMe = `<span><div>${content.data[i].type}</div><div>${'EOS'+ content.data[i].quantity}</div><div>${'$ ' + content.data[i].price}</div><div>${'$ ' +Number(content.data[i].price*content.data[i].quantity).toLocaleString('en')}</div></span>`
setState({...state, showMe});

but then when I try to put the jsx into the dom i get it as a string that shows the html tags instead of interpreting them但是当我尝试将 jsx 放入 dom 时,我将其作为字符串显示 html 标签而不是解释它们

{state.showMe}

I guess im saving the html as a string and not jsx?我想我将 html 保存为字符串而不是 jsx? If so how to save jsx instead of the string?如果是这样如何保存jsx而不是字符串?

I also tried我也试过

sellArray += <span><div>{content.data[i].type}</div><div>{'EOS ' + content.data[i].quantity}</div><div>{'$ ' + content.data[i].price}</div><div>{'$ ' +Number(content.data[i].price*content.data[i].quantity).toLocaleString('en')}</div></span>;

But the html just shows [object Object]但是 html 只显示[object Object]

If i have the values as objects in an array I can map over it and it works just fine, but i dont want to have to do that.如果我将值作为数组中的对象,我可以通过 map 处理它,它工作得很好,但我不想这样做。

const showMeArray = content.data.map((item: any) => <span><div>{item.type}</div><div>{'EOS ' + item.quantity}</div><div>{'$ ' + item.price}</div><div>{'$ ' +Number(item.price*item.quantity).toLocaleString('en')}</div></span>);

I dont understand why this works我不明白为什么这有效

You can display showMe state variable in dom by the use of dangerouslySetInnerHTML .您可以通过使用dangerouslySetInnerHTMLdom中显示showMe state 变量。

<div dangerouslySetInnerHTML={{ __html: state.showMe }}></div>

Here is the working demo for you这是给你的工作演示
https://stackblitz.com/edit/react-i9ha5h https://stackblitz.com/edit/react-i9ha5h

You can use babel to transform it你可以使用 babel 来改造它

npm install --save babel-core npm install --save babel-core

Then in your code然后在你的代码中

var babel = require('babel-core');
var Component = eval(babel.transform('<div><MyComponent /></div>').code);

Or you can use react-html-parser或者你可以使用react-html-parser

import React from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';

class HtmlComponent extends React.Component {
  render() {
    const html = '<div>Example HTML string</div>';
    return <div>{ ReactHtmlParser(html) }</div>;
  }
}

But this is generally bad practise when transform string to execuatable code但这在将字符串转换为可执行代码时通常是不好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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