React中Input组件onKeyPress事件无法获取event.key的问题
解决React Input组件onKeyPress中event.key undefined的问题
嘿,我一眼就看出问题出在哪了!你遇到的TypeError: Cannot read property 'key' of undefined,核心原因是子组件InputField没有把键盘事件对象传递给父组件的handleKeyPress方法。
错误原因分析
在InputField的render方法里,你写的箭头函数没有接收React自动传递的event参数,也没把它传给父组件的方法:
onKeyPress = {()=> this.props.testProp()}
这种写法下,父组件handleKeyPress(e)里的e就是undefined,自然读不到e.key啦。
第一步:修复事件参数传递
先把InputField的onKeyPress回调改成正确传递event的形式,有两种简洁写法:
写法1:显式传递event
class InputField extends Component { render(){ return( <input type="text" className="input-field" onKeyPress={(e)=> this.props.testProp(e)} // 把事件对象e传进去 /> ) } }
写法2:直接绑定父组件方法
因为React会自动把event作为第一个参数传给事件回调,你可以直接把父组件的方法传进去,省去箭头函数:
class InputField extends Component { render(){ return( <input type="text" className="input-field" onKeyPress={this.props.testProp} // React自动传递event参数 /> ) } }
第二步:实现回车键更新父组件状态
现在event能正常传递了,接下来修改父组件的handleKeyPress,判断是否按下回车键,同时用受控组件管理输入框内容,方便获取输入值:
class ToDoList extends Component { constructor(props) { super(props); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.state = { todoArr: [], inputValue: '' // 新增状态管理输入框内容 }; } // 同步输入框内容到父组件状态 handleInputChange(e) { this.setState({ inputValue: e.target.value }) } handleKeyPress(e){ // 判断是否按下回车键,且输入内容不为空 if(e.key === 'Enter' && this.state.inputValue.trim()){ this.setState(prevState => ({ todoArr: [...prevState.todoArr, prevState.inputValue], inputValue: '' // 新增后清空输入框 })) } } render(){ return( <div className="wrapper"> <p className = "title">todos</p> <InputField onKeyPress={this.handleKeyPress} onChange={this.handleInputChange} value={this.state.inputValue} ></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.onKeyPress} onChange={this.props.onChange} value={this.props.value} /> ) } }
这样修改后,当你按下回车键时,输入的内容就会被添加到todoArr里,同时清空输入框,完美实现你的需求~
内容的提问来源于stack exchange,提问作者Maksim
相关产品推荐
相关产品推荐

