【问题标题】:React: How to get children as string?React:如何将孩子作为字符串?
【发布时间】:2017-02-09 11:46:17
【问题描述】:

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

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

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

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

那么 MyDoc 现在是:

const myDoc = () => (
  <Code>
    <MyComponent title="MyTitle" />
  </Code>
)

但是由于Code里面的children是一个对象,所以不会渲染成字符串。

有没有办法做到这一点?或者可能是更好的解决方案?

【问题讨论】:

  • 如果您还记得那么远,您最终会得到什么解决方案。接受的答案对我来说立即失败。

标签: reactjs


【解决方案1】:

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

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

只是提一下,以防其他人也在尝试做文档并在这篇文章中绊倒。

【讨论】:

    【解决方案2】:

    试试这个:

    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')
    );
    

    【讨论】:

    • 安装它的好主意。我发现了一些使用它的错误(例如:当孩子是一组项目(兄弟姐妹)时)。然而,这是一个好的开始。谢谢!
    • 请尝试在您的答案中包含文本以与您发布的代码一起使用。额外的文字增加了上下文,有助于使您的答案更加具体。
    【解决方案3】:

    你真的没有重复。由于第一个&lt;MyComponent title="MyTitle" /&gt; 是(编译和)运行的代码,但第二个是您要显示的字符串。一旦从 JSX 编译为 JS,它们之间就没有太多相似之处,这使得以通用方式从另一个中获取一个充其量是困难的。

    我建议直接离开。

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多