我试图实现动态渲染的反应-本机图表套件,其中图表类型将设置在道具。
我想这样做
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
}} />
}有办法做这种事吗?
发布于 2019-11-27 09:46:34
如果您有一个简单的字符串组件(例如h1或a),那么您可以将它赋值给变量。
export function chart(props){
const Type = 'a';
return <Type />; // React.createElement('a') should also work
}但是,在您引用类的情况下,您可能会发现导入整个库更容易:
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
}据我所知,没有一种简单的方法可以从字符串中获取类定义引用(除了执行eval之外,这是一种糟糕的实践)。
https://stackoverflow.com/questions/59067192
复制相似问题