reactjs - 如何在处理程序中更改状态
问题描述
我有一个 React 项目,它正在使用 Recompose。假设我有一个表单,我提供了一个“withHandler”用于..
提交表单时如何更改 React 组件的状态?
解决方案
因此,假设表单是使用 提交的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 中处理事件的信息。我相信上面的链接将为您提供处理提交的表单所需的所有信息。
推荐阅读
- javascript - 通过鼠标移动在屏幕上书写特定文本
- bootstrap-4 - 使“主”类 div 用 Razor 填充整个页面
- javascript - 使用对象作为 Vue 选择选项
- angular - FullCalendar 5.1 中的定时事件,时间标签格式
- amazon-cloudformation - 在 CloudFormation/Serverless 中创建 AWS::S3::RecordSet 时如何引用 CloudFront 域名?
- java - 如果可扩展布局超出屏幕,则 ScrollView 显示布局
- python - 如何在包含基于json键的self关键字的类中定义__init__函数
- wpf - 将不同的 DataContext 设置为 WPF 中 ControlTemplate 中的元素
- excel - VBA Excel 2016 运行时错误 9:索引超出范围
- c# - UnitTestCoverage - 删除合同 dll 的 .netFramework 覆盖范围