Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

reactjs - 当用户使用Hooks在React上按下键时,如何执行功能?(How Can I exec a function when user press a key on React using Hooks?)

I need that my react component exec a function when user press a key (keyUp), but i have the next error:

(当用户按下一个键 (keyUp)时, 我需要我的react组件执行一个函数 ,但是我有下一个错误:)

react-dom.development.js:55 Uncaught Invariant Violation: Too many re-renders. 
React limits the number of renders to prevent an infinite loop.

I am using a hook to event's keyboard:

(我正在使用事件键盘的钩子:)

function useKey(key) {
  const [pressed, setPressed] = useState(false)
  const match = event => key.toLowerCase() == event.key.toLowerCase()
  const onDown = event => {
    if (match(event)) {  setPressed(true) }
  }
  const onUp = event => {
    if (match(event)) { setPressed(false) }
  }
  useEffect(() => {
    window.addEventListener("keydown", onDown)
    window.addEventListener("keyup", onUp)
    return () => {
      window.removeEventListener("keydown", onDown)
      window.removeEventListener("keyup", onUp)
    }
  }, [key])
  return pressed
}

and my component:

(和我的组件:)

function App() {
  const [state, setState] = useState("state")
  const key = useKey('ArrowUp')
  if(key){
    // TODO
    setState({...state})
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {state}
    </div>
  );
}

Code is here https://codesandbox.io/s/suspicious-ellis-zrgkt

(代码在这里https://codesandbox.io/s/suspicious-ellis-zrgkt)

  ask by yussenn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's your setState is causing issue.

(是您的setState引起问题。)

Move state update in useEffect hook, whenever there is change in key check if key is true then update your state.

(在useEffect挂钩中移动状态更新,只要密钥中有更改,请检查key是否为true,然后更新您的状态。)

function App() {
  const [state, setState] = useState("state")
  const key = useKey('ArrowUp')
  useEffect(() => {
    if(key) setState({...state});
  }, [key])
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {state}
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...