输入值更改时,我的“ onChange”功能未触发-使用React Hooks

时间:2019-08-14 06:37:02

标签: reactjs onchange react-hooks

我复制了以下代码,并做了一些小的修改。无论出于何种原因,我都无法键入该表格。放入一些日志后,我可以看到甚至没有调用handleSubmit函数。

我在更大的React-Redux应用程序的上下文中使用此组件。为了测试Redux周期是否以某种方式影响了此组件的渲染,我摆脱了connect redux函数,但是仍然-没有更改。请帮忙。

const Lose = props => {
  const [username, setUsername] = useState();

  const handleChangeUsername = e => {
    setUsername(e.target.value);
  };

  const handleSubmit = event => {
    alert(username);
    event.preventDefault();
  };

  return (
    <div className={'main_popup'}>
      <H3
        text={`Nice game! You obliterated: ${
          props.monstersKilled
        } monsters. Enter your name to have your badassery forever recorded`}
      />
      <form onSubmit={handleSubmit}>
        Username:
        <input type="text" value={username} onChange={handleChangeUsername} />
      </form>
    </div>
  );
};

const mapStateToProps = state => ({
  ...state.popUp,
  ...state.player
});

export default connect(mapStateToProps)(handlePopUp(Lose));

以下是调用上述组件的代码:

 class Player extends Component {
  componentDidUpdate(prevProps) {
    checkIfDead();
  }
  render() {
    return (
      <div
        style={{
          position: 'absolute',
          top: this.props.position[1],
          left: this.props.position[0],
          backgroundImage: `url('${
            this.props.status === 'HURT'
              ? walkSpriteHurt
              : this.props.status === 'LEVEL_UP_YELLOW'
              ? walkSpriteLevelUpYellow
              : this.props.status === 'LEVEL_UP_BLACK'
              ? walkSpriteLevelUpBlack
              : walkSprite
          }')`,
          backgroundPosition: this.props.spriteLocation,
          width: '40px',
          height: '40px'
        }}
      >
        <div style={{ position: 'absolute', bottom: '20px' }}>
          <progress
            id="health"
            value={this.props.stats.health}
            max={this.props.stats.totalHealth}
            style={{ width: '100px' }}
          />
        </div>
      </div>
    );
  }
}

function checkIfDead() {
  if (
    store.getState().player.stats.health <= 0 &&
    store.getState().player.dead === false
  ) {
    store.dispatch({ type: 'KILL_PLAYER' });
    store.dispatch({
      type: 'CHANGE_POP_UP',
      payload: {
        type: 'Highscore'
      }
    });
  }
}

const mapStateToProps = state => ({
  ...state.player,
  ...state.fire
});

export default connect(mapStateToProps)(handleKeyPress(Player));

1 个答案:

答案 0 :(得分:0)

好,我知道了!因此,表单被嵌套在已附加window.eventListener('keydown')的组件中。将事件侦听器移到其他组件后,React表单中的onChange函数再次开始工作。哇!

做到这一点。