reactjs - 无法在类组件 React.js 中使用 useState

标签 reactjs

我正在尝试在 react 中创建常量,如下所示:

const [firstFocus, setFirstFocus] = React.useState(false);
const [lastFocus, setLastFocus] = React.useState(false);

代码中使用的常量如下:
import React, { Component } from 'react'
import axios from 'axios'

import {
    Button,
    Card,
    CardHeader,
    CardBody,
    CardFooter,
    Form,
    Input,
    InputGroupAddon,
    InputGroupText,
    InputGroup,
    Container,
    Col
} from "reactstrap";

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            email: '',
            password: ''
        }
    }

    changeHandler = (e) => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = (e) => {
        e.preventDefault()
        console.log(this.state)
        axios.post('https://jsonplaceholder.typicode.com/posts', this.state)
            .then(response => {
                console.log(response)
            })
            .catch(error => {
                console.log(error)
            })
    }


    render() {
        const { email, password } = this.state
        **const [firstFocus, setFirstFocus] = React.useState(false);
        const [lastFocus, setLastFocus] = React.useState(false);**
        return (

            <div>
                <Col className="ml-auto mr-auto" md="4">
                    <Card className="card-login card-plain">
                        <Form onSubmit={this.submitHandler} className="form">
                            <CardHeader className="text-center">
                            </CardHeader>
                            <CardBody>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_email-85"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Email"
                                        type="text"
                                        name="email"
                                        value={email}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setFirstFocus(true)}
                                    // onBlur={() => setFirstFocus(false)}
                                    ></Input>
                                </InputGroup>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_lock-circle-open"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Password"
                                        type="password"
                                        name="password"
                                        value={password}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setLastFocus(true)}
                                    // onBlur={() => setLastFocus(false)}
                                    ></Input>
                                </InputGroup>
                            </CardBody>
                            <CardFooter className="text-center">
                                <Button
                                    block
                                    className="btn-round"
                                    color="info"
                                    type="submit"
                                    size="lg"
                                >
                                    Get Started
                    </Button>
                                <div className="pull-right">
                                    <h6>
                                        <a
                                            className="link"
                                            href="#pablo"
                                            onClick={e => e.preventDefault()}
                                        >
                                            Need Help?
                        </a>
                                    </h6>
                                </div>
                            </CardFooter>
                        </Form>
                    </Card>
                </Col>
            </div>
        )
    }
}

export default PostForm

但是,当我尝试这样做时,出现以下错误:

Invalid hook call. Hooks can only be called inside of the body of a function component.



我在那里为电子邮件和密码创建了另一个常量,它工作得很好,所以我不确定为什么我的 useState 常量不起作用。非常感谢任何帮助或指导,因为我对 react 非常陌生。谢谢!

最佳答案

在 react 中,我们有两种构建组件的方法:类和函数。
DOCS

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.


使用状态钩子(Hook):
import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
等效类示例:
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

关于reactjs - 无法在类组件 React.js 中使用 useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961065/

相关文章:

javascript - 在 react 组件内等待来自非 react 源的请求

javascript - 如何解决 React 警告 : Invalid argument supplied to oneOfType. 需要一个检查函数数组,但在索引 2 处收到未定义。?

reactjs - babel 7 不允许在装饰器和类之间使用 export 关键字。请使用 `export @dec class` 代替

reactjs - 如何使用 Axios 和 React 传递 Header JWT Token?

reactjs - 在 React 中使用 useMemo() 钩子(Hook)导致我的函数落后一步

javascript - Meteor React - 发布/订阅不起作用

spring - 在特定 URL 中实时加载 React App

javascript - 使用 redux-form 上传图片

javascript - react /MobX : Store values are undefined?

javascript - 在 React 状态中保持更新的对象关系