问题
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