我想序列化一个 React 元素(给定 props 的 React 组件实例)并在其他地方反序列化它。你为什么问?我希望能够通过标准输出从一个进程发送类并在另一个进程中呈现它。我也希望渲染的组件是交互式的,所以仅仅使用是ReactDOM.renderToString()
不够的......
我试过的:
- 将其序列化为字符串并
eval()
用于反序列化 - 分别为
JSON.stringify()
和使用自定义替换器和恢复器功能JSON.parse()
MyReactComponent.toString()
返回:
"function MyReactClass() {
_classCallCheck(this, MyReactClass);
_get(Object.getPrototypeOf(MyReactClass.prototype), 'constructor', this).apply(this, arguments);
}"
它不包含我的组件独有的任何方法(例如render()
或constructor()
)。
在 JS Bin 中看到这个示例代码:http : //jsbin.com/febuzupicu/edit? js,console, output