[英]is it possible to convert string to jsx component? React Native
I am trying to implement dynamic render of react-native-chart-kit where the chart type will be set in props.我正在尝试实现 react-native-chart-kit 的动态渲染,其中图表类型将在 props 中设置。
I thought of making it this way我想这样做
import { LineChart, BarChart, PieChart, ProgressChart, ContributionGraph, StackedBarChart} from 'react-native-chart-kit'
export function chart(props){
return <{props.type} data={props.data} //props.type is one of the imported components
width={Dimensions.get('screen').width}
height={220}
chartConfig={props.config}
style={{
marginVertical: 8,
borderRadius: 16
}} />
}
is there a way for something like this?有没有办法做这样的事情?
If you had a simple string component (eg h1
or a
) then you could assign it to a variable eg如果您有一个简单的字符串组件(例如
h1
或a
),那么您可以将它分配给一个变量,例如
export function chart(props){
const Type = 'a';
return <Type />; // React.createElement('a') should also work
}
In your case where you refer to a class however you might find it easier to import the entire library:在您引用类的情况下,您可能会发现导入整个库更容易:
import * as ChartKit from 'react-native-chart-kit'
export function chart(props){
if (ChartKit[props.type]) {
const Type = ChartKit[props.type];
return <Type data={props.data} //props.type is one of the imported components
width={Dimensions.get('screen').width}
height={220}
chartConfig={props.config}
style={{
marginVertical: 8,
borderRadius: 16
}} />
}
return null; // Or throw an error
}
As far as I'm aware there's no simple way to get the class definition reference from a string (aside from doing an eval
which is bad practice).据我所知,没有简单的方法可以从字符串中获取类定义引用(除了执行
eval
这是不好的做法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.