在React代码中使用Babel Transform [英] Use Babel Transform inside of React code

查看:673
本文介绍了在React代码中使用Babel Transform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为有效的JSX代码,然后将其注入到我的React组件中.

I'm trying to convert a string to valid JSX code, and then inject it into my React component.

const babel = require('babel-core')
let result = eval(babel.transform('<p className="greeting">Hello</p>').code)

但是我遇到了很多错误,因为我试图在浏览器中使用Babel:

But am getting hit with a wall of errors, because I'm trying to use Babel in the browser:

ERROR in ./~/babel-core/lib/api/node.js
Module not found: Error: Can't resolve 'fs' in '/Users/ben/Desktop/Work/code/ru-coding-challege/node_modules/babel-core/lib/api'
 @ ./~/babel-core/lib/api/node.js 72:10-23
 @ ./~/babel-core/index.js
 @ ./src/js/containers/app-container.js
 @ ./src/js/index.js
 @ multi (webpack)-dev-server/client?http://localhost:3000 ./src/js/index.js

...more similar errors

是的,我知道从字符串创建代码并注入代码很困难,但是D3动态创建元素(即,您不能以声明方式编写它们),例如:轴的值和数量滴答声根据数据而变化.我已经使用 htmltojsx 成功地将D3轴更改为JSX,但是返回了String.我需要将String转换为可注入代码的有效JSX组件.

Yes, I know creating code from a string and injecting it is frowned upon, but D3 creates elements dynamically (i.e. you can't write them declaratively) For example: axes whose values and number of ticks change based on the data. I've successfully changed the D3 axes into JSX with htmltojsx but that returns a String. I need to turn that String into valid JSX components that I can inject into my code.

正如Michael Lyons在下面指出的那样,我可以只使用dangerouslySetInnerHTML,但是除非所有其他方法都不起作用,否则我将尽量避免使用此选项.尽量保持在React范式之内.

As Michael Lyons states below, I could just use dangerouslySetInnerHTML, but I am trying to avoid this option unless everything else doesn't work. Trying to stay within the React paradigm as much as possible.

这是我组件的render方法的外观:

Here's how my component's render method would look:

<svg width='100%' height='600'>
  <g transform='translate(50, 50)'>
    <path d='...' className='path-0'></path>
  </g>
  {/* Insert JSX elements here. e.g. axes below */}
  {axes}
</svg>

这是我的webpack.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin')
const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: './src/js/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
  },
  devServer: {
    inline: true,
    contentBase: path.join(__dirname, 'dist'),
    port: 3000
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: 'src/html/index.html' }
    ]),
    new webpack.DefinePlugin({
      IN_BROWSER: true,
    }),
  ],
  module: {
    loaders: [
      {
        test: /\.scss$/,
        exclude: /(node_modules)/,
        loader: 'style-loader!css-loader!sass-loader'
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
}

推荐答案

与其将HTML转换为JSX,然后在客户端上使用babel在代码中进行呈现,还可以直接通过React组件来呈现该html.

Instead of translating HTML to JSX, then rendering with babel in your code while on the client, you could render that html directly through your React component.

Facebook的DOM元素实现为此用例内置了功能,您说对了,出于安全原因,通常对此不满意,因为它为

Facebook's DOM element implementation has built in functionality for this use-case, and you are right it is generally frowned upon for security reasons because it opens up vulnerabilities to cross-site scripting.

Facebook甚至将其标记为"dangerouslySetInnerHTML",以提醒开发人员这是危险的.

Facebook has even labeled it "dangerouslySetInnerHTML" to remind devs that this is dangerous.

因此,如果您具有字符串格式的HTML,则可以按以下方式在JSX中呈现它:

So if you have HTML in a string format, you can render that in JSX in a manner such as this:

getMarkup() {
  return { __html: '<p class="greeting">Hello</p>' }
}
render() {
  return <div dangerouslySetInnerHTML={this.getMarkup()} />;
}

这直接来自此处的React DOM元素文档:文档

This comes straight from the React DOM elements documentation here: Docs

此方法还应使您不必将d3输出转换为JSX

This method should also allow you to bypass having to convert your d3 output to JSX

介绍性句子

这篇关于在React代码中使用Babel Transform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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