React:如何将孩子作为字符串获取?

Gil*_*eno 5 reactjs

我正在为我们正在构建的几个组件编写文档,因此文档(也是一个反应组件)如下所示:

const myDoc = () => (
  <div>
    <MyComponent title="MyTitle" />
    <code className="language-jsx">
       {`<MyComponent title="MyTitle" />`}
    </code>
  </div>
)
Run Code Online (Sandbox Code Playgroud)

看到 MyComponent 上的重复项了吗?所以我创建了“代码”组件来处理这个问题:

const Code = ({ children }) => (
  <div>
    {children}
    <code>
       {children}
    </code>
  </div>
)
Run Code Online (Sandbox Code Playgroud)

那么 MyDoc 现在是:

const myDoc = () => (
  <Code>
    <MyComponent title="MyTitle" />
  </Code>
)
Run Code Online (Sandbox Code Playgroud)

但由于 Code 中的 Children 是一个对象,因此它不会呈现为字符串。

有办法实现这一点吗?或者也许有更好的解决方案?

小智 5

我也在编写文档,而且我也不想每次更改演示时都更改 markdown 文件。我想要类似 element.innerHTML 等价的东西。

我偶然发现了这个答案,并进一步搜索,我在 github 中发现了这个名为jsxToString的包。

只是提一下以防万一其他人也在尝试做文档并在这篇文章中犯了错误。


Mar*_*ite 1

尝试这个:

const MyComponent = ({
  title
}) => (
  <div>{title}</div>
)

const MyDoc = () => (
  <Code>
    <MyComponent title="My title" obj={{obj: {obj: 1}}}>
      <MyComponent title="My another component title">
        <MyComponent title="My another component title" />
      </MyComponent>
    </MyComponent>
  </Code>
)

const Code = ({
  children
}) => (
  <div>
    {children}
    <pre><code>
      {JsxString(children)}
      </code></pre>
  </div>
)

const JsxString = (component, counter = 0) => {
  let type = component.type.name;
  let props = component.props;
  let propsString = "";
  for (let key in props) {
    if (key !== "children") {
      let propValue = props[key];
      let value = "";
      if (propValue instanceof Object) {
        value = `{${JSON.stringify(propValue).replace(/['"]+/g, '')}}`;
      } else {
        value = `"${propValue}"`;
      }
      propsString += ` ${key}=${value}`;
    }
  }
  if (props.children) {
    counter += 2;
    var children = JsxString(props.children, counter);
    return `<${type}${propsString}>
${Array(counter).join(" ")}  ${children}
${Array(counter).join(" ")}</${type}>`;
  }
  return `<${type}${propsString} />`;
}

ReactDOM.render(
  <MyDoc />,
  document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)