簡體   English   中英

反應:在所有子組件上傳遞onClick函數

[英]React: Pass onClick function on all Children Components

當我單擊任何子級“ postItem”組件時,我想觸發一個onClick函數。 有了我現在擁有的功能,除非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;

通過地圖傳遞函數是否不正確?

這與地圖中的onClick無關。 記住,當您在ecma中思考時,函數是一流的:將函數作為prop傳遞過來與字符串或數組沒有什么不同,並且可以映射,對嗎?

問題似乎是傳遞給SocialFeed#showBox方法的參數。 您的方法定義為將showItem作為arg,但是onClick會將React SyntheticEvent對象作為其第一個arg傳遞。 從技術上講,您可以從中獲取target ,但這可能不是您想要顯示的框(可能不是)。

通常,您要做的就是將參數傳遞給事件處理程序 ,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM