鉴于这一组成部分:

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

const NewGoalInput = props => {
  return (
    <input type="text" onKeyUp={handleKeyUp}/>
  )
}

const handleKeyUp = (e) => {
  if (e.key === "Enter") {
    // TODO Add goal
  }
}

export default NewGoalInput

我如何添加一个构造函数,在其中我可以定义状态,而不必使用extends React.Component语法?

推荐答案

因为它是一个无状态组件,所以没有组件生命周期.

你必须扩展React.Component来创建一个有状态的组件,然后需要一个构造函数,你就可以使用state了.

Update

Hooks are a new feature proposal that lets you use state and other React > features without writing a class. They are released in React as a part of > v16.8.0

Stateless:

import React from "react"

const Stateless = ({name}) => (
  <div>{`Hi ${name}`}</div>
);

Stateful:

可以访问组件生命周期方法和本地状态.

class Stateful extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    const { count } = this.state;
    document.title = `You've clicked ${count} times.`;
  }

  componentDidUpdate() {
    const { count } = this.state;
    document.title = `You've clicked ${count} times.`;
  }

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

Using Hooks:

能够使用State HookEffect Hook.

如果您熟悉React类生命周期方法,可以将useEffect钩子视为componentDidMount、componentDidUpdate和componentWillUnmount的组合.

import React, { useState, useEffect } from "react";

const UsingHooks = () => {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You've clicked ${count} times.`;
  });

  return (
    // <> is a short syntax for <React.Fragment> and can be used instead of a wrapping div
    <>
      <p>You've clicked {count} times.</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </>
  );
}

Reactjs相关问答推荐

通过React/Esri应用程序中的SON配置时,小部件不会添加层

有正确的方法来设置我的金牛座应用程序的图标吗?

在一个blog函数中调用setState钩子

App.js中的H2组件不会动态呈现.这可能是什么问题?

无法在主组件的返回语句中呈现预期组件

如何使我的代码可以接受我想要的每一个链接

根据用户 Select 的注册类型更改表单字段

在reactjs中刷新页面时丢失状态值

使用获取的数据更新状态,但在try console.log 时它给出未定义

预期无限重新渲染但没有发生

获取更多数据后更新 DOM,而不刷新 React.js 中的页面

在MongoDB中,如何获取最后N条记录中字段不为空或不为空字符串的数据

在 Nextjs13 应用程序目录中呈现从 supabase 获取的数据

当每个元素都可拖动时,移动设备上的滚动列表出现问题

使用 react-markdown 组件时 Tailwind CSS 的问题

React js中不记名令牌中的空间问题

如何在 React 中使用 debounce hooks

如何禁用来自 React Native API 的某些特定项目的可touch 不透明度

是什么导致了这个令人惊讶的数组导致 React

React 似乎在触发另一个组件时重新渲染了错误的组件