简体   繁体   中英

How can I make it so that when a user types a letter the input would change to the next input field and so on?

So I am making kind of like a hangman type of app where I scramble a sentence and a user has to guess the sentence. There are multiple input fields that is restricted to one letter. I want to make it possible so when the user types a letter the input would change to the next input field and so on until the last input field. If anyone can steer me in the right direction it would be greatly appreciated.

const InputGrid = ({sentence, key}) =>{
    const [userInput, setUserInput] = useState('');
    const [word, setWord] = useState('');
    const [letters, setLetters] = useState([]);
    console.log(userInput);

    useEffect(() =>{
        // let word = sentence.split(' ');
        setWord(sentence);
        setLetters(word.split(''));
    }, [sentence, word]);


    const handleChange = (event) =>{
        setUserInput(event.currentTarget.value)
    }

    const successInput = {
        background: 'green'
    }

    return(
        <div>
            {letters.map(letter =>{
                return (<input
                    maxLength="1" 
                    type="text" 
                    key={key} 
                    className="grid"
                    onChange={handleChange} 
                />);
            })}
        </div>
    )
};

export default InputGrid;

You could store the inputs as refs and then focus the next one if a user types a character

import { useRef } from 'react'

// ...
const inputs = useRef([]);

const handleChange = (event, index) =>{
        // Check if the current input is not the last
        if (index +1 != inputs.current.length) {
            let input = inputs.current[index+1];
            // Focus the next input
            input.focus();
        }
        // Example handle change for your use case
        // Adding the new character to your current input
        setUserInput(userInput + event.currentTarget.value);
    }

return(
        <div>
            {letters.map((letter, index) =>{
                return (<input
                    maxLength="1" 
                    type="text" 
                    key={key} 
                    className="grid"
                    { /* Pass index to onChange event */ }
                    onChange={(event) => handleChange(event, index)}
                    ref={el => inputs.current[index] = el}
                />);
            })}
        </div>
    )

// ...

Take a look in the documentation of React refs for further explanation on how refs work. Answer of multiple refs: https://stackoverflow.com/a/56063129/9852454

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM