簡體   English   中英

我怎樣才能做到這一點,當用戶輸入一個字母時,輸入會更改為下一個輸入字段等等?

[英]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?

所以我正在制作一種類似於劊子手類型的應用程序,我在其中打亂一個句子,而用戶必須猜測這個句子。 有多個輸入字段僅限於一個字母。 我想讓它成為可能,所以當用戶輸入一個字母時,輸入將更改為下一個輸入字段,依此類推,直到最后一個輸入字段。 如果有人能引導我朝着正確的方向前進,將不勝感激。

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;

您可以將輸入存儲為 refs,然后在用戶鍵入字符時聚焦下一個

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>
    )

// ...

查看 React refs 的文檔以進一步解釋 refs 的工作原理。 多個參考的答案: https://stackoverflow.com/a/56063129/9852454

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM