首页 > 解决方案 > Rapid onChange 导致 OnClick 不注册

问题描述

我在 onChange 输入字段时设置状态,然后在 onClick 上有一个提交功能。如果我在最后一次输入后一秒钟左右单击它,则 onClick 根本不会注册。

我已经从不需要的组件中删除了所有内容,并留下了这个:

    import React, { Component } from 'react';
import { connect } from 'react-redux';
import Loader from '../utils/Loader';
import './CustomMenu.scss';
import {custom_getCategory} from '../../actions/customActions';
import propsDebug from '../utils/propsDebug';

class CustomMenu extends Component {

  constructor(props) {
    super(props);
    this.state = {
      input: "",
      customWords: [],
    }

  this.formToState = this.formToState.bind(this);
  this.submit = this.submit.bind(this);

}


formToState(e) {
  const {value, name} = e.target;
  this.setState({[name]: value});
}
submit() {
  const {input} = this.state;
  this.setState( state => {
    state.input = "";
  console.log("newState", state);
    return state;
  });
}

  render() {
    const {input, customWords} = this.state;


    return (
      <div className="CustomMenu">
        <input name="input" value={input} onChange={(e) => this.formToState(e)}/>
        <button onClick={(e) => {
          console.log("onClick");
          this.submit(e);
        }} style={{margin: "10px"}}>Add</button>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
    data: state[ownProps.reduxState],
    custom: state.custom,
  })

  export default connect(mapStateToProps, {custom_getCategory})(CustomMenu);

有什么想法可以解决这个问题吗?我觉得我以前多次使用这种模式没有问题 - 我不知道我错过了什么。

标签: reactjs

解决方案


<button onClick={(e) => (
  console.log("onClick");
  this.submit(e);
)} style={{margin: "10px"}}>Add</button>

改为使用隐式返回。


推荐阅读