简体   繁体   English

如何在反应 js 中将 props.children 转换为字符串

[英]How to convert props.children to string in react js

I want to convert react children to string.我想将反应儿童转换为字符串。 In the below example I am passing div, h2 and p as children to Example in Exampleclass.在下面的示例中,我将 div、h2 和 p 作为子级传递给 Exampleclass 中的 Example。 when I call props.children in Example it returns an array but I need a props.children in the string format so that I can use it in dangerouslySetInnerHTML.当我在 Example 中调用 props.children 时,它返回一个数组,但我需要一个字符串格式的 props.children,以便我可以在危险的 SetInnerHTML 中使用它。

import React, { Component } from "react";
import Example from "./example";
export default class Exampleclass extends Component {
  render() {
    return (
      <div>
        <p>in class</p>
        <Example> // passing div, h2 and p as children to Example
          <div>
          <h2>function</h2>
          <p>function</p>
          </div>
        </Example>
      </div>
    );
  }
}
import React from "react";

export default function example(props) {
  console.log("child", props.children); // returns array  but i need <div><h2>function</h2><p>function</p></div> here

  return <div dangerouslySetInnerHTML={{ __html: `${props.children}` }} />;    // returns [object Object]

}

It would be difficult to transform children object into some kind of a flat string with a JSX-a-like structure.children对象转换为某种具有类似 JSX 结构的扁平字符串是很困难的。 children is a complex object with a lot of nested fields. children是一个复杂的对象,有很多嵌套的字段。 You would have to convert it firstly to an array , then iterate over it, probably recursively, pick correct props and so on.您必须首先将其转换为array ,然后迭代它,可能是递归的,选择正确的道具等等。

However you could pass your children not as a children , but as a separate prop.然而,你不能错过你的孩子是儿童,但作为一个单独的道具。

 const Child = ({ child }) => { return <div dangerouslySetInnerHTML={{ __html: child }} />; }; const App = () => { const data = ` <div> <h2>function</h2> <p>function</p> </div> `; return <Child child={data} /> }; ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

Edit : You could, however, use renderToStaticMarkup function, but it will render only pure html (it will compile components into html).编辑:但是,您可以使用renderToStaticMarkup函数,但它只会呈现纯html (它将组件编译为 html)。 In your example you are passing only html elements so I guess it would be okey.在您的示例中,您只传递 html 元素,所以我想这会很好。

const markup = ReactDOMServer.renderToStaticMarkup(children);

return <div dangerouslySetInnerHTML={{ __html: markup }} />;

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

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