【问题标题】:How to convert string to React Component如何将字符串转换为 React 组件
【发布时间】:2021-08-20 10:37:07
【问题描述】:

我从后端获取了一个数据,其中包含组件名称,它们应该传递给 HOC 和路由

import Users from './Users/Users.lazy';
........

 // RequireAuth is the HOC
 <Switch>
     <Route path="/home" component={RequireAuth(Home)} />
     {(props.pagesData.length) && props.pagesData.map(item =>
         <Route exact path={`${item.PagePath}`} component={RequireAuth(`${item.PageName}`)} />
     )}

     <Redirect to="/home" />
 </Switch>

如何将Users(由item.PageName提供)之类的字符串转换为组件。

谢谢

【问题讨论】:

    标签: reactjs react-router react-hooks components


    【解决方案1】:

    尝试使用三元运算符。像这样;

     <Route exact path={`${item.PagePath}`} component={RequireAuth(item.PagePath === 'Users' ? Users : null)} />
    

    【讨论】:

    • 这可能是我最后的手段,但这可能是个问题,因为我会有很多页面/组件,这就是我将它们存储在数据库中的原因。谢谢
    • 来个组件图怎么样?
    • 我想我会使用您的解决方案,因为将字符串转换为 Component 可能存在安全风险。谢谢
    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2021-01-19
    • 2017-12-07
    相关资源
    最近更新 更多