ReactJS JSX toString() [英] ReactJS JSX toString()

查看:290
本文介绍了ReactJS JSX toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写基于React的文档网站。我想显示从我的框架中使用给定组件所必需的代码。同时我想显示实际的组件运行,就像一个并排的视图。



目前,我将组件添加为字符串参考实现和组件作为运行场景的JSX。这样的东西:

  var ButtonDoc = React.createClass({
render:function(){
let buttonComponent =(
< Button label =Add/>
);

let buttonCode =`< Button label =Add/>`;

return(
< div>
{buttonComponent}
< pre>< code> {buttonCode}< / code>< / pre>
< / div>
);
}
});

问题:有没有办法可以获得字符串表示形式给定的React组件,而不需要复制代码?



我期待着这样:

  var ButtonDoc = React.createClass({
render:function(){
let buttonComponent =(
< Button label =Add/>
);

let buttonCode =`$ {buttonComponent}`;

return(
< div>
{buttonComponent}
< pre>< code> {buttonCode}< / code>< / pre>
< / div>
);
}
}) ;

给定代码的输出是 object [object]

解决方案

由于我没有找到任何解决问题的方法,我最终创建了一个npm存储库来实现任务。



https:// github。 com / alansouzati / jsx-to-string



用法:

  import反应的反应; 
从'jsx-to-string'导入jsxToString;

let Basic = React.createClass({
render(){
return(
< div />
);
}
}); //这是你的反应组件

console.log(jsxToString(< Basic test1 =test/>))); //输出:< Basic test1 =test/>


I'm writing a documentation website based on React. I want to show the code that is necessary to use a given component from my framework. At the same time I would like to show the actual component running, like a side-by-side view.

Currently, I'm adding the component as a String for the reference implementation and the component as JSX for the running scenario. Something like this:

var ButtonDoc = React.createClass({
  render: function () {
    let buttonComponent = (
      <Button label="Add" />
    );

    let buttonCode = `<Button label="Add" />`;

    return (
      <div>
        {buttonComponent}
        <pre><code>{buttonCode}</code></pre>
      </div>
    );
  }
});

Question: Is there a way that I can get the string representation of the given React component without the need to replicate the code?

I'm expecting something like this:

var ButtonDoc = React.createClass({
  render: function () {
    let buttonComponent = (
      <Button label="Add" />
    );

    let buttonCode = `${buttonComponent}`;

    return (
      <div>
        {buttonComponent}
        <pre><code>{buttonCode}</code></pre>
      </div>
    );
  }
});

The output of the given code is object [object].

解决方案

As I did not find anything that solved my problem, I ended up creating a npm repository to achieve this task.

https://github.com/alansouzati/jsx-to-string

Usage:

import React from 'react';
import jsxToString from 'jsx-to-string';

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic test1="test" />)); //outputs: <Basic test1="test" />

这篇关于ReactJS JSX toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆