从String变量反应本机渲染组件 [英] React Native render Components from String variable

查看:63
本文介绍了从String变量反应本机渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者也许应该是一个问题,如何将字符串转换为JSX?

Or maybe the question should have been, How to convert string to JSX?

无论如何,我都试图在我的react native应用程序上进行性能破解,这需要我从字符串变量中呈现React native组件.

In any case, I am trying to do a performance hack on my react native app that requires me to render React native components from a string variable.

例如

let item = "<View>
  <Text>
      This is an item
  </Text>
</View>";

现在在我的渲染函数中,我想像这样渲染它:

Now in my render function, I want to render it like so:

render() {
    return (
      <View>
        {item}
      </View>
    );
}

现在,如果我尝试运行应用程序,则会出现错误,因为我正在尝试在View组件内渲染文本.如果我尝试在渲染之前将项目包装在文本中,它只会将项目以纯文本的形式呈现在屏幕上,而所有<View><Text>标签都作为字符串.

As it is now if I try to run the application it gives an error because I am trying to render text inside a View component. If I try to wrap the item inside text before rendering, It just renders the item as plain text on the screen, with all the <View> and <Text> tags as strings.

然后我该如何渲染它,以便字符串中的标签表现为正常的React Native组件,而不是仅仅以字符串形式出现?

How can I then render this so that the tags from the string behave as normal React Native component instead of just appearing as strings?

我搜索了所有内容,但没有找到解决方法.

I have searched all over but haven't found a solution.

我将不胜感激.

推荐答案

尝试以下两个软件包之一:

Try one of these two packages:

https://www.npmjs.com/package/acorn-jsx

https://www.npmjs.com/package/react-jsx-parser

两者都允许在运行中将字符串解析为jsx(没有机会在RN中进行测试,但是对于Web中的React可以正常工作)

Both allow to parse a string to jsx on the fly (Have no chance to test in RN, but for React in web works fine )

这篇关于从String变量反应本机渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆