使用虚拟键盘时 useState 的初始值未更新

Initial value for useState isn't updating when using Virtual Keyboard

这里是初学者。尝试 react-simple-keyboard 使用 Gatsby 和 React。

我用某种状态 (firstName: "Johnn") 初始化我的表单。这应该是初始状态。我希望用户能够修改这个名称,并将修改后的版本保存在状态中。

我在这里初始化我的状态:

 const [inputs, setInputs] = useState({
     firstName: "Johnn"
  })

当我单击该字段并按下虚拟键盘上的一个按钮(比如一个字母)时,它会删除整个字段的内容并将字母放在那里,而不是将字母添加到已经存在的内容中.另外:单击该字段并按退格键(在 react-simple-keyboard 上)不会执行任何操作。这是为什么?

import React, { useRef, useState, useContext, useEffect } from "react"
import styled from "styled-components"
import ReactDOM from "react-dom"
import Keyboard from "react-simple-keyboard"
import "react-simple-keyboard/build/css/index.css"
import Layout from "@components/layout"
import { useForm } from "react-hook-form"
import { Flex, Box } from "rebass/styled-components"
import Input from "@atoms/Input"

import {
  GlobalDispatchContext,
  GlobalStateContext,
} from "../context/GlobalContextProvider"

function App() {
  const dispatch = useContext(GlobalDispatchContext)
  const state = useContext(GlobalStateContext)

  const [inputs, setInputs] = useState({
    firstName: "Johnn",
    // firstName: state.customers[state.currentCustomer].firstName,
  })
  const [layoutName, setLayoutName] = useState("default")
  const [inputName, setInputName] = useState("default")

  const [isShiftPressed, setShiftPressed] = useState(false)
  const [isCaps, setCaps] = useState(false)
  const [isKeyboardVisible, setKeyboardVisible] = useState(false)

  const { register, handleSubmit, errors } = useForm()
  const keyboard = useRef()

  const onChangeAll = newInputs => {
    /**
     * Here we spread the inputs into a new object
     * If we modify the same object, react will not trigger a re-render
     */
    setInputs({ ...newInputs })
  }

  const handleShift = () => {
    const newLayoutName = layoutName === "default" ? "shift" : "default"
    setLayoutName(newLayoutName)
  }

  const onKeyPress = button => {
    if (isShiftPressed === true && !isCaps) {
      setShiftPressed(false)
      handleShift()
    }
    if (button === "{lock}") {
      setCaps(true)
    }
    if (button === "{shift}" || button === "{lock}") {
      setShiftPressed(true)
      handleShift()
    }
  }

  const onChangeInput = event => {
    const inputVal = event.target.value

    setInputs({
      ...inputs,
      [inputName]: inputVal,
    })

    keyboard.current.setInput(inputVal)
  }

  const getInputValue = inputName => {
    return inputs[inputName] || ""
  }

  return (
    <Layout>
      <Flex flexDirection="column" style={{ height: "100%" }}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Input
            id="firstName"
            name="firstName"
            value={getInputValue("firstName")}
            onFocus={() => {
              setInputName("firstName")
            }}
            placeholder={"First Name"}
            onChange={onChangeInput}
          />
        </form>

        <Keyboard
          keyboardRef={r => (keyboard.current = r)}
          inputName={inputName}
          layoutName={layoutName}
          onChangeAll={onChangeAll}
          onKeyPress={onKeyPress}
        />
      </Flex>
    </Layout>
  )
}

export default App

您可能需要使用 useEffect 钩子设置初始键盘值,并在后续更改中删除 keyboard.current.setInput(inputVal)

const {firstName} = input;
useEffect(() => {
  keyboard.current.setInput(firstName);
}, [firstName]);

这将确保在键盘实例中设置 firstName 的初始和后续更改。

代码沙箱:https://codesandbox.io/s/distracted-aryabhata-j3whs?file=/src/index.js