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

时间:2020-07-20 16:06:57

标签: javascript reactjs context-api react-simple-keyboard

初学者在这里。试图让react-simple-keyboard与Gatsby&React合作。

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

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

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

当我单击该字段并按下虚拟键盘上的按钮(例如一个字母)时,它会删除整个字段的内容,并将字母放在此处,而不是将字母添加到该字段中。另外:单击该字段并按Backspace(在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

1 个答案:

答案 0 :(得分:0)

您可能需要使用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