简体   繁体   English

循环遍历 html 元素 jsx 数组

[英]loop through an array of html elements jsx

I have an array of html elements, lets say messages.我有一组 html 元素,可以说是消息。 And i want to render them as follow:我想将它们呈现如下:

this.state.messages.push('<span className={Styles.success-message}>User successfully added</span>');

And in render method:在渲染方法中:

     {this.state.messages.map((value, index) => {
         return <div key={index}>{value}</div>
     })}

But during my rendering instead of getting the message with appropriate style im getting the entire element as string:但是在我的渲染过程中,我没有以适当的样式获取消息,而是将整个元素作为字符串: 在此处输入图片说明

if you have html tags in state array you can use like this-如果您在状态数组中有 html 标签,您可以像这样使用 -

class App extends React.Component {
  state = {
    messages: [
      `<span>User successfully added</span>`,
      `<span>User successfully removed</span>`
    ]
  };
  render() {
    return (
      <>
        {this.state.messages.map((item,index) => (
          <h3 key={index} dangerouslySetInnerHTML={{ __html: item }} />
        ))}
      </>
    );
  }
}

Live working demo https://codesandbox.io/s/quizzical-leftpad-p3hib现场工作演示https://codesandbox.io/s/quizzical-leftpad-p3hib

Do it using dangerouslySetInnerHTML feature from React.使用 React 中的 risklySetInnerHTML 特性来做这件事。 There is an example in the below link.下面的链接中有一个例子。

https://reactjs.org/docs/dom-elements.html https://reactjs.org/docs/dom-elements.html

First of all, you should never mutate state , which is ground rule of react.首先,你永远不应该改变 state ,这是反应的基本规则。

Coming to issue, you're pushing a string , instead what you should be doing is问题来了,你正在推动一个 string ,而不是你应该做的是

let messages =  [];
messages.push(<span className={Styles.success-message}>User successfully added</span>)
this.setState({ messages })

and then loop through this array in render() method like然后在 render() 方法中循环遍历这个数组,如

this.state.message.map((value, messageIndex) => <div key={messageIndex} > {value} </div> ) this.state.message.map((value, messageIndex) => <div key={messageIndex} > {value} </div> )

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

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