首页 > 解决方案 > 如何在处理程序中更改状态

问题描述

我有一个 React 项目,它正在使用 Recompose。假设我有一个表单,我提供了一个“withHandler”用于..

提交表单时如何更改 React 组件的状态?

标签: reactjsrecompose

解决方案


因此,假设表单是使用 提交的button,并且我们onClick在按钮上有一个属性。

这是一个非常简单的示例,但希望向您展示如何使用onClick. 请记住,这是一个可以应用于 HTML 元素的属性。您可以在此处阅读onClick 属性

import React, { Component } from 'react';

import React from "react";
import { render } from "react-dom";
import Component from "react-component-component";

class Button extends Component {
  state = {
    counter: 0
  };

  handleButtonClick = () => {
    this.setState({
      counter: this.state.counter + 1
    });
  };

  getButton = () => {
    const { text } = this.props;

    return (
      <button
        onClick={this.handleButtonClick}
      >
        {text}
        {this.state.counter}
      </button>
    );
  };

  render() {
    return <div>{this.getButton()}</div>;
  }
}

render(
  <Button text="press me to increase counter: " />,
  document.getElementById("root")
);

可以在这里看到以下内容:https ://codesandbox.io/s/ly11qv0vr7

还有一个关于处理事件的反应文档的非常好的示例。您可以在此处阅读有关在 react 中处理事件的信息。我相信上面的链接将为您提供处理提交的表单所需的所有信息。


推荐阅读