首页 > 解决方案 > 未检测到反应点击

问题描述

我有一个组件,我想通过使用 onClick 属性来监听它的点击事件。简单的东西。但是,当我单击组件时,单击事件不会触发。

我的组件结构如下(我使用 styled-components,但这不应该相关):

// this comes from my UI library

const Icon = styled.div`
  /* some css properties */ 
`

const Search = () => (
  <Icon>
    /* this is an svg imported from the react-icons library */
    <MdSearch />
  </Icon>
)


// this is where I use the stuff from my UI library

class SomeComponent extends Component {
  handleClick = () => {
    // do something
  }

  render() {
    return (
      <div>
        /* some other stuff */
        <Search onClick={this.handleClick} />
      </div>
    )
  }
}

只有当我在 Search 组件中向下展开道具时才会检测到点击,如下所示:

const Search = (props) => (
  <Icon {...props}>
    /* this is an svg imported from the react-icons library */
    <MdSearch />
  </Icon>
)

但是,我对这种行为完全感到困惑。为什么我不能让任何组件直接可点击?但是必须手动将 onClick 属性传递给下一个 DOM 元素?如果就是这样,有没有比传播道具更优雅的解决方案?因为那会弄乱我的整个 UI 库... :-)

标签: reactjs

解决方案


以这种{...props}方式需要:

<Icon {...props}>
    /* this is an svg imported from the react-icons library */
    <MdSearch />
</Icon>

以便您传递给Search(即onClick={this.handleClick})的道具实际上被传递并附加到(功能)组件内部的组件。如果没有...props,这些道具会被传入,但实际上并没有“附加”到任何东西上,或者无论如何都不会被使用。

如上所示不使用扩展运算符大致相当于创建以下函数:

foo(x) { return 1 }

并想知道为什么不同的值x不会影响foo.

希望澄清和帮助:-)


推荐阅读