打字稿如何在父组件中传递道具

时间:2021-03-20 05:02:51

标签: reactjs typescript react-router-dom

我正在练习打字稿。对于 setAuthenticated(valueFromChild) 行,我有错误“类型 'void' 不能分配到类型 'boolean'”,并且“...不能分配到类型 'IntrinsicAttributes & { children?: ReactNode; }'。”对于我在这里将道具传递给子组件的所有地方(,)。如何修复错误?

import { FunctionComponent, useState } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Navbar from './Components/navbar.component';
import './App.css';
import { ThemeProvider } from '@material-ui/core/styles';
import theme from './Theme/theme';
import Login from './Components/login.component';
import Register from './Components/register.component';

const App: FunctionComponent = () => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const handleAuth = (valueFromChild: boolean): boolean =>
    setIsAuthenticated(valueFromChild);
  return (
    <ThemeProvider theme={theme}>
      <BrowserRouter>
        <Navbar isAuthenticated={isAuthenticated} />
        <Switch>
          <Route
            exact
            path="/login"
            render={(props) => <Login {...props} handleAuth={handleAuth} />}
          />
          <Route
            exact
            path="/register"
            render={(props) => <Register {...props} handleAuth={handleAuth} />}
          />
        </Switch>
      </BrowserRouter>
    </ThemeProvider>
  );
};

export default App;

1 个答案:

答案 0 :(得分:2)

const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const handleAuth = (valueFromChild: boolean): boolean =>
    setIsAuthenticated(valueFromChild);

您是说 handleAuth 必须返回 boolean。但是调用 setIsAuthenticated 会返回 void。您可能只想让 handleAuth 返回 void。或者,您可以省略返回类型,让 Typescript 正确推断。

const handleAuth = (valueFromChild: boolean): void =>
    setIsAuthenticated(valueFromChild);
<块引用>

“...不能分配到类型 'IntrinsicAttributes & { children?: ReactNode; }'。”对于我在这里将 props 传递给子组件的所有地方 (,)。

您的组件 LoginRegister 似乎不接受任何道具。他们接受 handleAuth 道具吗?

它们的定义应该类似于:

export interface AuthProps {
  handleAuth: (value: boolean) => void;
}

export const Login: React.FunctionComponent<AuthProps> = ({handleAuth}) => { ...

export const Register: React.FunctionComponent<AuthProps> = ({handleAuth}) => { ...

您从 (props) => 传递的道具是 RouteComponentProps,其中包括 matchlocation 等。您可以将这些包含在您的 {{ 1}} 和 Login 组件。但是如果你不需要在组件中使用这些 props 那么你可以不传递它们。

Register