小编典典

反应:如何让孩子成为绳子?

reactjs

我正在为我们正在构建的几个组件编写文档,因此doc(也是一个react组件,看起来像这样:

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中的子级是对象,因此不会将其呈现为字符串。

有没有办法做到这一点?还是更好的解决方案?


阅读 247

收藏
2020-07-22

共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')
);
2020-07-22