react-tsx学习过程的报错记录

244 阅读1分钟

1. Type '...' is not assignable to type 'IntrinsicAttributes'. Property '...' does not exist on type 'IntrinsicAttributes'

  • 报错原因: 父子组件传值时未在子组件定义props类型
  • 解决方法: typescript进行类型定义
//父组件
<RegisterForm changeStatus = { changePage } />

// 子组件
interface RegisterFormProps {
  changeStatus?: Function,
}

const RegisterForm: React.FC<RegisterFormProps> = ({ changeStatus }) => {

2. Type 'Function | undefined' is not assignable to type 'MouseEventHandler | undefined'

  • 报错原因: 函数式组件,父子组件传方法时解构直接传递方法名,因为类型可能是Function,也可能是undefined ,所以报类型错误
  • 解决方法: 最好直接用props代替,方法使用 props.方法名 进行调用
  const LoginForm: React.FC<RegisterFormProps> = ({你的方法}) => {
  <div onClick= {你的方法} ><div/>
  }
  // 改为
  const LoginForm: React.FC<RegisterFormProps> = (props: any) => {
  <div onClick= {() => 你的方法()} ><div/>
  }

3. # useNavigate() may be used only in the context of a Router component

  • 报错原因: 不能在路由组件外部调用useNavigate hook
  • 解决方法: 使用BrowserRouter包裹你的组件
  • 实测无法使用数组路由定义,RouterProvider包裹也没用, 后续找到新方式再追加更新
<BrowserRouter> 
   <你的组件/>
</BrowserRouter> 
//  你的组件
      (<div>...</div>
   <Routes>
       <Route/>
   </Routes>
      <div>...</div>)