猿问

单击时未触发 onClick 事件 - 反应

我是超级新手,我正在努力让我的 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,

};

根据答案,问题似乎是 Badge 不是 HTML 元素。


慕盖茨4494581
浏览 196回答 2
2回答

斯蒂芬大帝

传递给的值onClick需要是一个函数。filterCategories(c.category)filterCategories&nbsp;立即调用并将其返回值(undefined因为没有return语句)传递给onClick.undefined&nbsp;不是函数。创建一个filterCategories使用您想要的参数调用的函数(例如 with&nbsp;bind,或者只使用函数表达式或箭头函数)并传递它。此外,Badge不是 HTML 元素。如果您的组件没有将onClickprop传递给 HTML 元素,则它不会在 DOM 中执行任何操作。

幕布斯7119047

<div style={categoriesStyle}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {posts.map(({ node: c }) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tabIndex="0"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={c.id}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={() => filterCategories(c.category)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; role="button"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onKeyDown={filterCategories}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Badge value={c.category} category={c.category} color="#fff">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {c.category}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Badge>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ))}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答