【React】React Hook “Form.useForm“ cannot be called in a class component. React Hooks must be called

不可以在class声明的组件中去使用,useState,useForm是React Hooks的实现,只能用于函数组件。==如果我需要在class声明的组建中去使用该如何?

 

在 Class 组件 下,需要通过 ref 获取数据域,通过ref获取的控制实例可使用API-FormInstance提供的所有方法,formRef = React.createRef();

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Form } from 'antd';
class LoginForm extends Component {
    formRef = React.createRef()
    changeCode = () => {
    	// 此处可用
        this.formRef.current.resetFields();
    }
    render() {
        return (
            <Form ref={this.formRef} ></Form>
        )
    }
}
export default withRouter(LoginForm);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这个错误提示的意思是,`useHistory` 这个 Hook 只能在函数组件和自定义 Hook 中使用,不能在类组件中使用。因为 HooksReact V16.8 引入的新特性,而类组件并不支持 Hooks。 如果你想在类组件中使用路由的 `history` 对象,可以使用 `withRouter` 高阶组件。`withRouter` 接收一个组件作为参数,并返回一个新的组件。新的组件会将路由的 `history` 对象作为 `props` 传递给被包裹的组件。 具体用法如下: 1. 首先,在需要使用 `history` 对象的类组件中,导入 `withRouter` 高阶组件: ```javascript import { withRouter } from 'react-router-dom'; ``` 2. 然后,使用 `withRouter` 包裹组件: ```javascript class MyComponent extends React.Component { render() { const { history } = this.props; return ( <React.Fragment> <button onClick={() => history.push('/new-route')}> Navigate to New Route </button> </React.Fragment> ); } } export default withRouter(MyComponent); ``` 在上面的例子中,我们使用 `withRouter` 包裹了 `MyComponent` 类组件,并将包裹后的组件导出。这样,`MyComponent` 组件就可以通过 `this.props.history` 访问 `history` 对象了。 需要注意的是,`withRouter` 包裹后的组件会在路由变化时重新渲染,因此可能会造成性能问题。如果你需要在类组件中频繁地访问 `history` 对象,建议将类组件转换为函数组件,并使用 `useHistory` 钩子来获取 `history` 对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值