2

I am trying to disable spaces in the input text field using onChange event and react-hooks. I'm saving the email input in state. The function in onChange event dispatches action, passing e.target as its input. However as soon as the dispatch occurs, the input field gets reset. I have tested the input field and it is working fine but when I click the keyboard space button then event.keyCode and event.which gives me undefined value.

import React, {useReducer} from 'react';

const initialState = {
    email: ''
};

function reducer(state, action) {
    switch (action.type) {
        case 'email':
            return {
                ...state,
                email: action.payload
            };
        default:
            throw new Error();
    }
}

const Login = () => {
    const [state, dispatch] = useReducer(reducer, initialState);
    const handleChange = (event) => {
        if (event.keyCode == 32) {
            return false;
        }
        dispatch({ type: event.target.name, payload: event.target.value.trim() });
    }
    return (
        <div className="container">
            <input 
                type="email"
                name="email"
                value={state.email}
                onChange={handleChange}
                placeholder="Enter Email"
            />
        </div>
    )
}

export default Login;
4

1 回答 1

6

那是因为change不是键盘事件。

如果您想要按下的键,请尝试使用onKeyDown, 。onKeyPressonKeyUp


例如

const Login = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const handleChange = event => {
    dispatch({ type: event.target.name, payload: event.target.value.trim() });
  };
  const handleKeyDown = event => {
    if (event.keyCode === 32) {
      event.preventDefault();
    }
  };
  return (
    <div className="container">
      <input
        type="email"
        name="email"
        value={state.email}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        placeholder="Enter Email"
      />
    </div>
  );
};

于 2020-01-05T10:48:02.567 回答