reactjs - 未检测到反应点击
问题描述
我有一个组件,我想通过使用 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 库... :-)
解决方案
以这种{...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
.
希望澄清和帮助:-)
推荐阅读
- amazon-web-services - 如何根据表中的值在 AWS 中触发警报?
- python - 如何从另一个函数停止while true循环
- python - 从币安获取历史数据
- jhipster - JHipster Registry - 部署到 ECS 的问题
- c++ - Visual Studio Code 无法同时编译 cpp 和 Cuda (cu) 文件
- python - 使用 Python 估计延迟微分方程的最佳参数
- css - 使用 JSDOM 编辑 CSS 样式表
- css - React app / CSS:变换和动画功能的问题
- reactjs - 使用 Typescript 响应上下文语法以加载 Spinner
- javascript - 无法将原始 SQL 转换为续集