Ben*_*ros 5 javascript eval ecmascript-6 reactjs react-native
我看到很多人在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} />);
}
Run Code Online (Sandbox Code Playgroud)
这可以迅速成为许多代码行,我想做这样的事情:
return (React.createElement(route.id, {propsToPass}));
Run Code Online (Sandbox Code Playgroud)
这在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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1228 次 |
| 最近记录: |