首页 > 解决方案 > 在 onClick 事件之前在页面加载时调用 Reactjs 函数

问题描述

功能在页面加载我的代码时工作,如下
所示

import React, { Component } from "react";
import ExtnButton from "./Button";
class MovieList extends Component {
  handleDelete = index => {
    console.log("inside handleDelete:");
  };
 render() {
    return (
      <React.Fragment>
     <ExtnButton handleDelete={this.handleDelete} index={index} />
      </React.Fragment>
    );
  }
}
export default MovieList;


孩子

import React, { Component } from "react";
class Button extends Component {
  state = {};
  render() {
    return (
      <button
        onClick={this.props.handleDelete(this.props.index)}
        className="btn btn-danger"
      >
        Delete
      </button>
    );
  }
}
 export default Button;

但是在页面加载函数handleDelete调用时没有任何点击事件

标签: reactjsfunctiononclick

解决方案


错误的:

onClick={this.props.handleDelete(this.props.index)}

正确的:

onClick={() => this.props.handleDelete(this.props.index)}

推荐阅读