React:在所有子组件上传递onClick函数

时间:2018-04-29 02:48:15

标签: javascript reactjs

当我点击我的任何一个孩子时,我想触发一个onClick函数" postItem"组件。根据我现在的情况,点击的组件不会做任何事情,除非onClick函数在map函数之外(例如在新的单独组件中)

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;

通过地图传递函数是不正确的?

1 个答案:

答案 0 :(得分:1)

这与您在地图中的onClick无关。请记住,当你在ecma中思考时,函数是一流的:传递一个函数作为一个prop与一个字符串或数组没什么不同,那些可以映射,对吗?

问题似乎是传递给SocialFeed#showBox方法的参数。您的方法定义为将showItem作为arg,但onClick将传递React SyntheticEvent对象作为其第一个arg。虽然从技术上来说可以从中获取target,但这可能是您想要显示的内容(可能不是),也可能不是。

您通常想做的事情是pass in an argument to the event handler,例如:

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