使用浏览器路由React TypeScript 16.8传递道具

时间:2019-07-20 06:50:13

标签: reactjs typescript

这是作为路线之一加载的组件。我已经在类型名称AppProps中将companyName的类型声明为字符串,然后用<AppProps>告诉组件该类型,然后在html中使用了{companyName}。感觉不错,但我无法理解如何从BrowserRouter传递属性。是在这里插入钩子还是我只是想念东西?

import React from 'react';
import logo from '../images/logo.svg';


type AppProps = {
  companyName: string
}

const Home: React.FC<AppProps> = ({companyName}) => {
  return (

    <div className="home-grid">
      <div className="logo">
        <h1><a href="/"><img src={logo} alt="My Logo" /></a></h1>
        <h2 className="strapline">{companyName}</h2>
      </div>
    </div>

  );
}

export default Home;

这是路由器

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

import Home from './home';
import NotFound from './error';

const Router: React.FC = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path = '/' component = {Home} />
        <Route component = {NotFound}/>
      </Switch>
    </BrowserRouter>
  );
}

export default Router;

1 个答案:

答案 0 :(得分:0)

使用renderchildren代替component

https://reacttraining.com/react-router/web/api/Route/render-func

https://reacttraining.com/react-router/web/api/Route/children-func

<Route exact path="/"
  render={routeProps => (
    <Home
      {...routeProps}
      companyName="Company Name"
    />
  )}
/>