Keypress无法记录所有击键

时间:2017-06-30 11:43:08

标签: javascript reactjs

我正在尝试捕获textarea中的击键并尝试使用onKeyUp,onKeyPress,onKeyPressCapture,onKeyDown,onKeyDownCapture等属性。所有这些似乎都错过了一些关键条目:

enter image description here

当我输入一个新密钥时,其中一个之前未显示的密钥按顺序显示。

由于排队延迟,我想我可能需要延迟控制台日志。但这实际上并没有解决潜在的问题。有谁知道为什么会发生这种行为?

这是父(App)和子组件(TypeArea)

class App extends React.Component {
  constructor (props) {
    super(props)
    // sets up this.props to function

    this.state = {
      textbox_in_parent_state: 'string passed from state of Parent(App)',
      someVar: 'parent_constructor_state',
      text_from_textarea: ''
    }

    this.handler = this.handler.bind(this)
    this.text_capture_from_parent = this.text_capture_from_parent.bind(this)
  }

  text_capture_from_parent(eventObject) {
    this.setState({
      text_from_textarea: eventObject.target.value
    })
    console.log(this.state.text_from_textarea)
  }


  render() {
    return (
      <div>
        <div className="container">
            <Header />
          <div className="row">
            <div className="col-sm-6">
              <TypeArea textcapture={this.text_capture_from_parent}
              />
            </div>
            <div className="col-sm-6">
              <MarkdownPreview />
            </div>
          </div>
        </div>

      {/* <div style={{textAlign: 'center'}}>*/}
      {/* <h1>App component written in client/components/App.jsx</h1>*/}
      {/* </div>*/}

      </div>
    )
  }
}

export default App

儿童

import React from 'react';

class TypeArea extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      textbox_text: 'string from state of child "TypeArea"'
    }
    console.log(this.state.textbox_text)
  }

  render() {
    return (
      <div>
        <h1>Typing Area</h1>

        <div className="form-group">

          <textarea className="form-control" id="textbox" rows="25" placeholder="Type Here" onKeyPressCapture={this.props.textcapture}>

          </textarea>

          <button onClick={this.props.passdown}>Click me</button>

        </div>

      </div>);
  }
}

export default TypeArea

1 个答案:

答案 0 :(得分:1)

text_capture_from_parent(eventObject) {
  this.setState({
    text_from_textarea: eventObject.target.value
  })
  console.log(this.state.text_from_textarea)
}

this.setState()是异步的,并且在设置状态后直接调用console.log(..),此时状态可能尚未成功更改。但幸运的是this.setState(..)在设置新状态时提供回调。所以你可以这样称呼它:

this.setState({
  text_from_textarea: eventObject.target.value
}), () => {
  console.log(this.state.text_from_textarea);
});

你应该看到实际值。