首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以将字符串转换为jsx组件?React Native

是否可以将字符串转换为jsx组件?React Native
EN

Stack Overflow用户
提问于 2019-11-27 09:41:45
回答 1查看 658关注 0票数 1

我试图实现动态渲染的反应-本机图表套件,其中图表类型将设置在道具。

我想这样做

代码语言:javascript
复制
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
            }} />
}

有办法做这种事吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-27 09:46:34

如果您有一个简单的字符串组件(例如h1a),那么您可以将它赋值给变量。

代码语言:javascript
复制
export function chart(props){
   const Type = 'a';
   return <Type />; // React.createElement('a') should also work
}

但是,在您引用类的情况下,您可能会发现导入整个库更容易:

代码语言:javascript
复制
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之外,这是一种糟糕的实践)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59067192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档