React应用onSearchChange事件无响应问题的排查与解决
React RoboFriends搜索框onSearchChange无响应问题解决
问题
开发React应用RoboFriends时,实现搜索框的onSearchChange功能遇到异常:向搜索栏输入内容时,本地控制台无任何输出(包括预设的console.log('Hello? Is this thing on?')),搜索过滤功能完全未按预期生效,判断是组件间通信出现问题。
相关代码
App.js
import React, { Component } from "react"; import CardList from './CardList'; import { robots } from './robots'; import SearchBox from './SearchBox'; import './App.css'; class App extends Component { constructor() { super() this.state = { robots: robots, searchfield: '' } } onSearchChange = (event) => { this.setState({ searchfield: event.target.value }) console.log('Hello? Is this thing on?') } render() { const filteredRobots = this.state.robots.filter(robots =>{ return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase()); }) return ( <div className='tc'> <h1 className='f1'>RoboFriends</h1> <SearchBox onSearchChange={this.onSearchChange}/> <CardList robots={filteredRobots} /> </div> ); } } export default App;
SearchBox.js(修复后代码)
import React from "react"; const SearchBox = ({ searchfield, onSearchChange} ) => { return ( <div className='pa2'> <input className='pa3 ba b--green bg-lightest-blue' type='search' placeholder='search robots' onChange={onSearchChange} /> </div> ) } export default SearchBox
解决方法
问题根源在SearchBox组件的props接收环节:原本将父组件App传递的onSearchChange属性误写为Searchchange(缺少前缀“on”),导致子组件无法正确绑定父组件的事件处理函数。
将props参数修正为onSearchChange后,输入框的onChange事件能正常触发父组件的onSearchChange方法,控制台输出恢复,搜索过滤功能也正常生效。
内容的提问来源于stack exchange,提问作者juan chavez
相关产品推荐
相关产品推荐

