React Native render Components from String variable

自作多情 提交于 2020-05-16 04:02:07

问题


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

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.

For instance,

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>
    );
}

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.

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.

I will appreciate any suggestions.


回答1:


If you put object instead of string you can easily set it inside view. But if you want to use string, you have to write a converter and extract each element as string and check and convert to it's equivalent view.
If your views have props you have to convert them also(it will be a little bit harder!)




回答2:


Try one of these two packages:

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

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

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 )



来源:https://stackoverflow.com/questions/51608770/react-native-render-components-from-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!