【问题标题】:How to render react component determined by string in TSX如何在 TSX 中渲染由字符串确定的反应组件
【发布时间】:2016-08-21 22:21:00
【问题描述】:

我想实现基于url中hash变化的导航。

例如对于 url index.html#HomePage,应用程序将加载 HomePage 组件。

import { HomePage } from '../components/homepage'
import { AnotherPage } from '../components/anoterpage'


export class NavigationFrame extends React.Component<any, State> {
    constructor(props) {
        super(props);
        this.state = { pageName: this.pageNameFromUrl() };
    } 

    onHashTagChanged = () => {
       this.setState({pageName: this.pageNameFromUrl()});
    }


    public render() {
         var Page = this.state.pageName as any;
        return <Page /> //this renders <homepage /> when this.state.pageName = "HomePage";
   }
}

有什么方法可以根据字符串动态创建组件吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:
    class CustomComponent extends React.Component{
      render(){
        return (
          var DynamicComponent = this.props.component;
          return <DynamicComponent />;
        )
      }
    }
    

    将其导入您的文件并像下面这样使用,

     return (
          <CustomComponent component={this.state.pageName} />
     );
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2020-01-08
      • 2019-01-07
      • 2022-01-04
      • 2017-03-18
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多