[英]Typescript React - use MouseEvents without passing it to child element
Can I use Mouse Events on whole React Element or I have to pass it to child element to get it work?我可以在整个 React 元素上使用鼠标事件还是必须将其传递给子元素才能使其工作? After several functions components where I passed my handleEvent function I want to know if it's possible without getting a TypeScript error.在我传递了我的handleEvent函数的几个函数组件之后,我想知道是否有可能没有出现TypeScript错误。 My code is really simple我的代码真的很简单
<Tile onHover={handleHover} name="Random name"/>
As your Title
component does not expect an onHover
prop, it will just be ignored.由于您的Title
组件不需要onHover
道具,它只会被忽略。 The event you want to use is rather onMouseOver
, which works on most HTML elements ( according to documentation ):您要使用的事件是onMouseOver
,它适用于大多数 HTML 元素(根据文档):
All HTML elements, EXCEPT:
<base>
,<bdo>
,<br>
,<head>
,<html>
,<iframe>
,<meta>
,<param>
,<script>
,<style>
, and<title>
所有 HTML 元素,除了:<base>
、<bdo>
、<br>
、<head>
、<html>
、<iframe>
、<meta>
、<param>
、<script>
、<style>
和<title>
What you could do is the following, in the Title
component:您可以在Title
组件中执行以下操作:
export const Tile: React.FC<{ name: string, onHover: SomeType }> = ({ name }) => {
return (
<div className="tile-wrapper" onMouseOver={onHover}>
<h1 className="tile-header>
{name}
</h1>
</div>
)
}
What you want is to combine React.DOMAttributes<HTMLElement>
with your custom props using an intersection.您想要的是使用交集将React.DOMAttributes<HTMLElement>
与您的自定义道具结合起来。 That will avail all the DOM events to your custom component, without having to manually pass it in.这会将所有 DOM 事件都用于您的自定义组件,而无需手动将其传入。
export const Tile: React.FC<{ name: string } & React.DOMAttributes<HTMLElement>> = ({ name, ...events }) => {
return (
<div className="tile-wrapper" {...events}>
<h1 className="tile-header>
{name}
</h1>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.