点击时未触发onClick事件-React

时间:2019-10-24 21:58:35

标签: javascript reactjs gatsby

我是新手,我正在努力使我的onClick工作。当页面呈现时,我看到被调用(多次,具体取决于数组中的项目数),但没有单击。

const BlogPage = props => {
          const posts = props.data.allContentfulPost.edges;
          const postsStable = props.data.allContentfulPost.edges;
          const categoriesStyle = {
            marginBottom: '8px',
          };

          const filterCategories = category => {
            console.log('here', category);
            // this.posts = this.posts.filter(p => p.catergory === category);
          };.

        return (
        <div style={categoriesStyle}>
            {posts.map(({ node: c }) => (
              <Badge onClick={filterCategories(c.category)}
                  key={c.id}
                  category={c.category}
                  color="#fff">
                  {c.category}
               </Badge>
             ))}
         </div>
        );
    };

我尝试过:

onClick={() => filterCategories(c.category)} 

onClick={() => {
                  filterCategories(c.category);
                }}

const Badge = ({ children, category = 'Other', color = '#4a4a4a' }) => {
  return (
    <Container background={pillColor(category)} color={color}>
      {children}
    </Container>
  );
};

Badge.propTypes = {
  children: PropTypes.node.isRequired,
  category: PropTypes.string,
  color: PropTypes.string,
};
  

根据答案看来,问题在于徽章不是   HTML元素。

2 个答案:

答案 0 :(得分:4)

传递给onClick的值必须是一个函数

filterCategories(c.category)立即调用filterCategories 并将其返回值(undefined因为没有return语句)传递给onClick

undefined不是函数。

创建一个函数,该函数使用所需的参数调用filterCategories(例如,使用bind,或者仅使用函数表达式或箭头函数),然后传递该函数。


此外,Badge不是HTML元素。如果您的组件未将onClick属性传递给HTML元素,则它将在DOM中不做任何事情。

答案 1 :(得分:0)

这就是我最终要做的。可能不是最好的解决方案。

import typing
import json


def tenants_from_json(json_string: str) -> typing.Iterable["Tenant"]:
    tenants = [
        Tenant.from_dict(tenant_dict)
        for tenant_dict in json.loads(json_string)
    ]
    return tenants