简体   繁体   English

使用字符串反应native native元素

[英]react native create element with string

I see a lot people creating a route mapping in React native similar to the below: 我看到很多人在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} />);
}

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.' 这在React Native中不起作用,因为显然'不允许将字符串作为React Native中的第一个参数,因为这些参数用于常规React中的html标记。

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). 如果我提供ReactClass作为第一个参数,或者使用eval(route.id)(但我知道这可能很危险),我得到了它的工作。

How can I create a React Native element with a string? 如何使用字符串创建React Native元素?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM