React组件按钮点击触发console.log无响应问题求助
排查并解决React按钮点击无响应问题
我来帮你搞定这个按钮点击没反应的问题,看了你的代码后,发现几个核心问题,咱们一步步修正:
问题1:函数组件Card无法访问this且未接收事件处理函数
你的Card是函数式组件,它没有类组件那样的this上下文,所以按钮里写onClick={this.addRental}完全找不到这个方法。而且父组件也没把点击事件的处理函数传递给Card。
修正Card组件:
修改Card,让它接收一个onAddRental的props,然后把按钮的点击事件绑定到这个props上:
var Card = props => ( <div> <div> <img src={props.image} height="164px" width="246px" alt="Rental property" /> </div> <button onClick={props.onAddRental}>Add Rental</button> </div> )
同时别忘了给Card的propTypes加上这个函数类型的校验:
Card.propTypes={ image: PropTypes.string, onAddRental: PropTypes.func.isRequired // 新增事件函数的类型校验 }
问题2:父组件未将事件处理函数传递给Card
在父组件Airbnblocation的render方法里,渲染Card的时候,需要把this.addRental作为props传递过去,这样Card才能拿到点击事件的处理逻辑。另外你map里的参数名重复了((locations, idx)),改成location更清晰:
render() { let locations = this.state.locations.map((location, idx) => { return( <Card key={idx} image={location.image} onAddRental={this.addRental} /> ) }) return ( <div> {locations} </div> ) }
可选优化:移除冗余的this绑定
你在constructor里写了this.addRental = this.addRental.bind(this);,但同时用了箭头函数定义addRental(addRental = () => { ... }),箭头函数会自动绑定当前组件的this,所以这个bind语句是多余的,可以删掉:
constructor(props){ super(props); this.state= { locations: airbnbs }; // 删掉这行:this.addRental = this.addRental.bind(this); }
完整修正后的代码
import React, { Component } from 'react'; import airbnbs from './airbnbs.json'; import PropTypes from 'prop-types'; var Card = props => ( <div> <div> <img src={props.image} height="164px" width="246px" alt="Rental property" /> </div> <button onClick={props.onAddRental}>Add Rental</button> </div> ) Card.propTypes={ image: PropTypes.string, onAddRental: PropTypes.func.isRequired } class Airbnblocation extends Component{ constructor(props){ super(props); this.state= { locations: airbnbs }; } addRental = () => { console.log("hi"); } render() { let locations = this.state.locations.map((location, idx) => { return( <Card key={idx} image={location.image} onAddRental={this.addRental} /> ) }) return ( <div> {locations} </div> ) } } export default Airbnblocation;
现在点击按钮应该就能在控制台看到"hi"了!
内容的提问来源于stack exchange,提问作者Travis Scott
相关产品推荐
相关产品推荐

