react native create element with string

*爱你&永不变心* 提交于 2020-01-03 13:04:12

问题


I see a lot people creating a route mapping in React native similar to the below:

if (route.id === 'Blah') {
    return  (<Blah prop1={this.method} prop2={this.other method} />);
} else if (route.id === 'OtherView') {
    return (<OtherView prop1={this.method} />);
}

this can quickly become many lines of code, I'd like to do something like this:

return (React.createElement(route.id, {propsToPass}));

This doesn't work in React Native as apparently 'strings are not allowed as the first parameter in React Native since those are meant to be used for html tags in regular React.'

So how can this be done? I got it working if I supply a ReactClass as the first param, or with eval(route.id) (but I know that can be dangerous).

How can I create a React Native element with a string?


回答1:


You could setup an allowed components namespace:

var routeComponents = {
  "Blah": Blah,
  "OtherView": OtherView
}

if(routeComponents[route.id]) {
  return React.createElement(routeComponents[route.id], {propsToPass});
} else {
  // Error
}


来源:https://stackoverflow.com/questions/34002382/react-native-create-element-with-string

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