动态组件在React中不起作用

时间:2019-07-04 13:08:58

标签: reactjs react-router

我想在React中添加一个动态组件,但是它不起作用。我得到了正确的组件名称,但是看起来我的变量无法使用:

componentDidMount() {
    const currentLocation = this.props.location.pathname;
    let route_name = 'Dashboard';
    for (let i = 0; i < Route.length; i++) {
      if (Route[i].path == currentLocation) {
        route_name = Route[i].name;
        break;
      }
    }
    this.setState({
      route_name: route_name
    });
  }

  render() {
    return (
      <div className="admin-content">
        <this.state.route_name />
      </div>
    );
  }

1 个答案:

答案 0 :(得分:2)

为了直接按名称渲染组件,需要先将其分配给变量,然后再渲染

componentDidMount() {
    const currentLocation = this.props.location.pathname;
    let route_name = 'Dashboard';
    for (let i = 0; i < Route.length; i++) {
      if (Route[i].path == currentLocation) {
        route_name = Route[i].name;
        break;
      }
    }
    this.setState({
      route_name: route_name
    });
  }

  render() {
    const RouteName = this.state.route_name;
    return (
      <div className="admin-content">
        <RouteName/>
      </div>
    );
  }