【问题标题】:rendering components in div with react router使用反应路由器在 div 中渲染组件
【发布时间】:2016-08-10 18:06:51
【问题描述】:

我正在开发一个新项目,并且对 React 非常陌生。我们正在使用打字稿(TSX)。到目前为止,我有一个index.html 文件,其 div 的 id 为“root”。我有一个main.tsx 文件,我相信它是用于我的主要组件的。这是那个的代码

/// <reference path="../../../../typings/main.d.ts"/>

require('file?name=[name].[ext]!../../index.html');

/*----------- STYLESHEETS -----------*/
require('flexboxgrid/css/flexboxgrid.css');

/*=============================================>>>>>
= MODULES =
===============================================>>>>>*/

import * as React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, browserHistory  } from 'react-router';

/*----------- ROUTE COMPONENTS -----------*/
import Root from './common/root.tsx';
import Home from './home/home.tsx';
import Login from './login/login.tsx';
//
// /*= End of MODULES =*/
// /*=============================================<<<<<*/

 render((
   <Router history={browserHistory}>
     {/** ###### HOME ROUTE ###### */}
     <Route path="/" component={Root}>
       <IndexRoute component={Home}/>
       <Route path="/login" component={Login}/>
     </Route>
     {/** ###### END HOME ROUTES ###### */}
   </Router>
 ), document.getElementById('root'));

我不确定如何处理我的 root.tsx 文件,以便它显示在我的根 div 中。到目前为止,这就是我的 root.tsx 文件。

"use strict";

import React from 'react';

class Root extends React.Component {
  render() {
    return(
        <div>
            <h1>About page!</h1>
        </div>
    )
  }
}
export default Root;

【问题讨论】:

  • 您的代码令人困惑。第一个块是什么,第二个块是什么?为什么第一个被注释掉了?
  • 除了被注释掉之外,代码看起来还不错。您是否在控制台中遇到任何错误?
  • 它被注释掉了,因为它根本不起作用,我正在尝试其他事情。现在取消注释。是的,我有一些错误,但似乎很重要的是 root.tsx?f149:5 Uncaught TypeError: Cannot read property 'Component' of undefined
  • 您可以尝试在您的 root.tsx 中将 import React from 'react' 更改为 import * as React from 'react';

标签: reactjs typescript react-router


【解决方案1】:

根据您评论中的错误描述

root.tsx?f149:5 未捕获类型错误:无法读取属性“组件” 未定义的

Reactroot.tsx 的第 5 行(如下)未定义,因此您的import 语句肯定有一些问题:

class Root extends React.Component

我建议以与您在 main.tsx 中相同的方式导入它。

import * as React from 'react'

而不是

import React from 'react';

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 2018-08-26
    • 2017-12-23
    • 2018-07-26
    • 2019-04-25
    • 2023-04-03
    • 2018-06-02
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多