[英]Returned dynamic string as JSX, rendered as imported components
Suppose I have some process that generates some JSX dynamically but as a literal string, is it possible to return it as JSX that renders imported components , Material UI in this case?假设我有一些动态生成一些 JSX 但作为文字字符串的进程,是否可以将其返回为呈现导入组件的 JSX,在这种情况下为 Material UI?
With the below I can only get unstyled markup to display.使用下面的内容,我只能显示无样式的标记。
import * as React from 'react';
import { Button } from '@material-ui/core';
export default class Testsp extends React.Component<ITestspProps, {}> {
public render(): React.ReactElement<ITestspProps> {
return <div dangerouslySetInnerHTML={this.someConvolutedProcess()} />
}
someConvolutedProcess() {
let generatedJSX = '<Button color="primary">Hello World... Again</Button>';
return {__html: generatedJSX};
}
}
With the below I have to provide element as JSX, not a string在下面我必须提供元素作为 JSX,而不是字符串
ReactDOMServer.renderToStaticMarkup(element)
I know my approach is weird but I have a niche case我知道我的方法很奇怪,但我有一个小众案例
There is no built-in option to generate JSX from a string (string-to-JSX).没有内置选项可以从字符串(字符串到 JSX)生成 JSX。
Note that you actually want to generate React element ( React.createElement
) from a string (as JSX is only syntactic sugar )请注意,您实际上想从字符串生成 React 元素(
React.createElement
)(因为 JSX 只是语法糖)
dangerouslySetInnerHTML
accepts only HTML elements, not JSX . dangerouslySetInnerHTML
只接受 HTML 元素,不接受 JSX 。ReactDOMServer
is for rendering component to static markup, ie JSX-to-string , JSX-to-HTML . ReactDOMServer
用于将组件渲染为 static 标记,即JSX-to-string , JSX-to-HTML 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.