[英]react native create element with string
我看到很多人在React native中创建路由映射,类似于下面的内容:
if (route.id === 'Blah') {
return (<Blah prop1={this.method} prop2={this.other method} />);
} else if (route.id === 'OtherView') {
return (<OtherView prop1={this.method} />);
}
这可以迅速成为许多代码行,我想做这样的事情:
return (React.createElement(route.id, {propsToPass}));
这在React Native中不起作用,因为显然'不允许将字符串作为React Native中的第一个参数,因为这些参数用于常规React中的html标记。
那么怎么做呢? 如果我提供ReactClass作为第一个参数,或者使用eval(route.id)(但我知道这可能很危险),我得到了它的工作。
如何使用字符串创建React Native元素?
您可以设置允许的组件命名空间:
var routeComponents = {
"Blah": Blah,
"OtherView": OtherView
}
if(routeComponents[route.id]) {
return React.createElement(routeComponents[route.id], {propsToPass});
} else {
// Error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.