简体   繁体   中英

React: Pass onClick function on all Children Components

I want to fire an onClick function when I click on any of my children "postItem" components. With what I have now, the clicked components won't do anything, unless the onClick function is outside the map function (such as in a new separate component)

import React, { Component } from "react";
import axios from "axios";
import PostItem from "./postItem";
import "../styles/socialFeed.css";

class SocialFeed extends Component {
  constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.showBox = this.showBox.bind(this);
  }

  showBox(postItem) {
    console.log(this);
  }

  componentDidMount() {
    this.Posts();
  }

  Posts() {
    axios
      .get(
        "randomapi"
      )
      .then(res => {
        const posts = res.data.data;
        this.setState({ posts });
      });
  }

  render() {
    let { posts } = this.state;
    let allPosts = posts.map(post => (
      <PostItem key={post.id} {...post} onClick={this.showBox} />
    ));
    return <div className="social-feed">{allPosts}</div>;
  }
}

export default SocialFeed;

is it incorrect to pass a function through a map?

This has nothing to do with your onClick being inside a map. Remember that when you're thinking in ecma, functions are first-class: passing a function around as a prop is no different than a string or an array, and those are okay to map, right?

The problem appears to be the arguments passed to the SocialFeed#showBox method. Your method is defined as taking showItem as the arg, but onClick will pass the React SyntheticEvent object as its first arg. While you technically can get the target from that, this may or may not be what you want to show the box (probably not).

What you'll usually want to do, is pass in an argument to the event handler , eg:

<PostItem key={post.id} {...post} onClick={() => this.showBox(post)} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM