我是ReactJs的新手,我正在尝试从字符串中渲染组件,这是我的代码:
import React from 'react';
import * as Babel from 'babel-standalone';
var input = 'import React from 'react';
class First extends React.Component {
render () {
return (
<h1>First Component</h1>
);
}
}';
export default First;
class App extends React.Component {
render() {
var output = Babel.transform(input, { presets: ['react', 'es2015'], plugins: ["transform-runtime"]}).code;
const code = output.replace("'use strict';", "").trim();
eval(code);
return (
<div>
<h1>Hello</h1>
<First/>
</div>
);
}
}
export default App;
但是它会抛出一个错误:“未捕获的ReferenceError:require未定义”。如何渲染已编译的字符串或解决此错误?感谢。
这里是来自输出的字符串:
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var First = function (_React$Component) {
_inherits(First, _React$Component);
function First() {
_classCallCheck(this, First);
return _possibleConstructorReturn(this, (First.__proto__ || Object.getPrototypeOf(First)).apply(this, arguments));
}
_createClass(First, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'h1',
null,
'First Component'
);
}
}]);
return First;
}(_react2.default.Component);
exports.default = First;