React onClick报错:预期监听器为函数,实际传入字符串类型
React onClick 报错:Expected onClick listener to be a function
问题原因
报错Expected onClick listener to be a function, instead got a value of string type源于两个核心问题:
- Plant组件中input的onClick写法错误:你用双引号包裹了函数,导致它被解析成字符串,而非有效的函数引用。
- handleUpdate作用域限制:
handleUpdate函数定义在WaterList组件内部,Plant组件无法直接访问它,需使用父组件传递的onClick属性。
修复方案
1. 修正Plant组件的input onClick
移除双引号,直接使用父组件传递的props.onClick——父组件已经帮你绑定了正确的plant._id参数,无需在子组件中重复处理。
2. 保留父组件的正确写法
父组件中Plant标签的onClick={() => handleUpdate(plant._id)}写法合规,保持不变即可。
修改后的代码
WaterList组件(无需修改)
// 更新浇水日期的函数 function handleUpdate(id) { setUpdatedItem((prevInput) => { return { ...prevInput, waterDate: {newWaterDate} } }) submitData(id); console.log(updatedItem); } return ( <div className="water-list"> <h2>Water Me!</h2> <p>check off to reset water schedule and remove from list</p> <ul className="water-list__plants"> { waterList(plants).map(plant => <li key={plant._id}> <Plant name={plant.name} img={plant.img} waterFrequency={plant.waterFrequency} _id={plant._id} onClick={() => handleUpdate(plant._id)} ></Plant> </li>) } </ul> </div> );
Plant组件(修改input部分)
const Plant = (props) => ( <li className="plant" id={props._id}> <div className="plant__img-wrapper"> <img src={props.img} alt={props.name} className="plant__img" /> </div> <div className="plant__text-wrapper"> <h3 className="plant__name">{props.name}</h3> <p>Water me every {props.waterFrequency} days, please</p> </div> <label className="plant__care-form"> {/* 修复:移除双引号,直接使用props.onClick */} <input onClick={props.onClick} type="checkbox" name="checkbox" /> <FontAwesomeIcon icon="fa-solid fa-check" /> </label> </li> );
补充说明
- React事件处理器必须是函数类型,不支持原生HTML的字符串形式事件绑定。
- 父组件通过箭头函数绑定参数的写法是正确的,点击时会自动传入对应的
plant._id。
内容的提问来源于stack exchange,提问作者Allyson Smith
相关产品推荐
相关产品推荐

