【问题标题】:How to change state in a handler如何在处理程序中更改状态
【发布时间】:2019-08-28 06:59:49
【问题描述】:

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

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

【问题讨论】:

  • 如果您发布一个示例和代码来说明您正在谈论的内容,将会有所帮助。

标签: reactjs recompose


【解决方案1】:

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

这是一个非常简单的示例,但希望向您展示如何使用onClick 更新状态。请记住,这是一个可以应用于 HTML 元素的属性。你可以阅读它the onClick attribute here

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多