这是它从字符串内容工作的方式,无需像其他人建议的那样将组件作为静态链接代码嵌入到包中。
import React from 'react';
import { Button } from 'semantic-ui-react';
import createReactClass from 'create-react-class';
export default class Demo extends React.Component {
render() {
const s = "return { render() { return rce('div', null, rce(components['Button'], {content: this.props.propA}), rce(components['Button'], {content: 'hardcoded content'})); } }"
const createComponentSpec = new Function("rce", "components", s);
const componentSpec = createComponentSpec(React.createElement, { "Button": Button });
const component = React.createElement(createReactClass(componentSpec), { propA: "content from property" }, null);
return (
<div>
{component}
</div>
)
}
}
React 类规范在字符串 s 中。请注意以下几点:
rce 代表React.createElement,并在调用createComponentSpec 时作为第一个参数给出。
components 是一个额外组件类型的字典,在调用createComponentSpec 时作为第二个参数给出。这样做是为了您可以提供具有冲突名称的组件。
例如字符串 Button 可以解析为标准 HTML 按钮,或语义 UI 中的按钮。
您可以使用https://babeljs.io 轻松为s 生成内容,如https://reactjs.org/docs/react-without-jsx.html 中所述。本质上,字符串不能包含 JSX 内容,并且必须是纯 JavaScript。这就是 BabelJS 通过将 JSX 翻译成 JavaScript 所做的事情。
你需要做的就是用rce替换React.createElement,并通过components字典解析外部组件(如果你不使用外部组件,你可以跳过字典的东西)。
这里和上面的代码是等价的。相同的 <div> 有两个语义 UI Buttons。
JSX 渲染()代码:
function render() {
return (
<div>
<Button content={this.props.propA}/>
<Button content='hardcoded content'/>
</div>
);
}
BabelJS 将其翻译成:
function render() {
return React.createElement("div", null, React.createElement(Button, {
content: this.props.propA
}), React.createElement(Button, {
content: "hardcoded content"
}));
}
然后按照上面的说明进行替换:
render() { return rce('div', null, rce(components['Button'], {content: this.props.propA}), rce(components['Button'], {content: 'hardcoded content'})); }
调用 createComponentSpec 函数将为 React 类创建规范。
然后使用createReactClass 转换为实际的 React 类。
然后通过React.createElement 实现。
您需要做的就是从主组件render func 返回它。