【问题标题】:Typescript how to pass props in parent component打字稿如何在父组件中传递道具
【发布时间】:2021-06-17 11:11:18
【问题描述】:

我正在练习打字。对于 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;

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:
    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; }'。”对于我在这里将道具传递给子组件的所有地方(,)。

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

    它们的定义应该类似于:

    export interface AuthProps {
      handleAuth: (value: boolean) => void;
    }
    
    export const Login: React.FunctionComponent<AuthProps> = ({handleAuth}) => { ...
    
    export const Register: React.FunctionComponent<AuthProps> = ({handleAuth}) => { ...
    

    您从(props) =&gt; 传递的道具是RouteComponentProps,其中包括matchlocation 等。您可以将这些包含在您的LoginRegister 组件的道具类型中。但是如果你不需要在组件中使用这些道具,那么你可以不传递它们。

    render={() => <Login handleAuth={handleAuth} />}
    

    【讨论】:

    • 谢谢琳达。
    猜你喜欢
    • 2022-06-10
    • 2021-11-10
    • 2019-09-25
    • 1970-01-01
    • 2020-06-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多