【问题标题】:Typescript and React: Initializing RouteComponentProps members in ReactTypescript 和 React:在 React 中初始化 RouteComponentProps 成员
【发布时间】:2020-07-08 23:04:41
【问题描述】:

我目前正在学习 Typescript 和 React,并且目前坚持能够正确访问道具的“匹配”成员。更具体地说,我在初始化从 RouteComponentProps 接口实现的变量时遇到了问题。

为了简单起见,我有以下 3 个文件和相应的组件(路径*)只是用文本渲染一个标题:

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/App';

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('roots')
);

app.tsx

import React from 'react';
import {BrowserRouter as Router, Route, Switch, RouteComponentProps} from 'react-router-dom';

import Path1 from './Path1';
import Path2 from './Path2';
import Nav from './Nav'

class App extends React.Component<RouteComponentProps> {
  render(): JSX.Element{
    return (
      <Router>
        <div className="App">
          <Nav history={this.props.history} location={this.props.location} match={this.props.match}/>
          <Switch>
            <Route path="/" exact component={Home} name="Home"/>
            <Route path="/path1" exact component={Path1} name="path1"/>
            <Route path="/path2" exact component={Path2} name="path2"/>
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App

Nav.tsx

import React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';

class Nav extends React.Component<RouteComponentProps>{
  render(): JSX.Element {
    return (
      <div className="Nav">
        {this.props.match.path}
        <ul className="NavLinks">
          <Link to="/">
            <li>Home</li>
          </Link>
          <Link to="/Path1">
            <li>Path1</li>
          </Link>
          <Link to="/Path2">
            <li>Path2</li>
          </Link>
        </ul>
      </div>
    );
  }
}

基本思想是,在单击每个链接时,Nav 组件仅根据用户所在的页面更新页面顶部的文本。我之所以将导航条码放在原来的位置,是因为它可以在将来添加更多路线时节省时间。

问题
我的问题是我需要在 index.tsx 中传递初始道具,但是我似乎找不到有关如何初始化接口 RouteComponentProps 中的道具的任何信息。或者,如果我做错了(或代码中的任何其他内容),请告诉我。我是 react/typescript 方面的新手,我想第一次学习正确的方法,不要重新养成坏习惯。

【问题讨论】:

    标签: reactjs typescript react-router react-component


    【解决方案1】:

    关于做得更好,我建议使用功能组件而不是类组件。

    功能组件也可以让您使用react hooks。你可以从 hooks 中获取locationhistorymatch

    interface MatchParams {
      name: string
    }
    
    const App = (): React.ReactElement => 
      const history = useHistory()
      const location = useLocation()
      const match = useRouteMatch<MatchParams>()
    
      return (
        <Router>
          <div className="App">
            <Nav history={history} location={location} match={match} />
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2018-07-23
      • 2020-05-16
      • 2022-01-17
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      相关资源
      最近更新 更多