我看到很多人在 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
}
关于javascript - 用字符串 react native 创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002382/