【问题标题】:React, having trouble getting event.key from onKeyPress input event反应,无法从 onKeyPress 输入事件中获取 event.key
【发布时间】:2018-10-31 02:20:11
【问题描述】:

我在从输入 onKeyPress 事件中获取 event.key 时遇到问题,当我在输入字段中输入时出现此错误 - TypeError: Cannot read property 'key' of undefined

计划是在子输入组件中按下回车时更新父状态。

class ToDoList extends Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.state = {
      todoArr: [],
    };
  }

  handleKeyPress(e){
    console.log(e.key);
  }

  render(){
    return(
        <div className="wrapper">
          <p className = "title">todos</p>
          <InputField testProp={this.handleKeyPress}></InputField>
          <div className = "filter-wrap">
            <ItemsLeft></ItemsLeft>
            <Filter></Filter>
            <ClearCompleted></ClearCompleted>
          </div>
        </div>
      )
  }
}

class InputField extends Component {
  render(){
    return(
        <input type="text" className="input-field" onKeyPress = {()=> this.props.testProp()}/>
      )
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    如果你想要这种方式,你应该通过 () =&gt; this.props.testProp() 来破坏孩子中的代码,你应该像这样传递参数 (e) =&gt; this.props.testProp(e)

    这就是我的方式

    class ToDoList extends Component {
      constructor(props) {
        super(props);
        this.handleKeyPress = this.handleKeyPress.bind(this);
        this.state = {
          todoArr: []
        };
      }
    
      handleKeyPress(e) {
        console.log(e.key);
      }
    
      render() {
        return (
          <div className="wrapper">
            <p className="title">todos</p>
            <InputField testProp={this.handleKeyPress} />
          </div>
        );
      }
    }
    
    class InputField extends Component {
      render() {
        return (
          <input
            type="text"
            className="input-field"
            onKeyPress={this.props.testProp}
          />
        );
      }
    }
    

    你可以在这里测试 :) https://codesandbox.io/s/6n2jp8yzy3

    如果你想查看控制台,左下角有一个按钮可以打开它。

    通过这样做,回调接收输入提供的所有参数,因此您不需要自己编写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2022-12-14
      • 2021-09-21
      • 2020-02-17
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多