点击后尝试访问按钮上的数据集时,我得到这个^错误。
linkProvider = (ev: React.SyntheticEvent<EventTarget>) => {
console.debug('ev.target', ev.target.dataset['ix']) // error
}
// in render
providers.map((provider, ix) => (
<button key={provider} data-ix={ix} onClick={this.linkProvider}>{provider}</button>
))
任何想法如何使其发挥作用?
答案 0 :(得分:6)
问题在于Element
,document
,window
可以是EventTarget
。您应该检测到EventTarget
if是否为元素。所以在你的情况下代码应该工作
linkProvider = (ev: React.SyntheticEvent<EventTarget>) => {
// If event target not an HTMLButtonElement, exit
if (!(ev.target instanceof HTMLButtonElement)) {
return;
}
console.debug('ev.target', ev.target.dataset['ix'])
}
短暂的
linkProvider = (ev: React.SyntheticEvent<HTMLButtonElement>) => {
console.debug('ev.target', ev.currentTarget.dataset['ix'])
}
我还添加了示例here
答案 1 :(得分:1)
结合@Efe和@fatemefazli提供的两个建议,我找到了一个有效的解决方案:
供参考,这是界面及其与target
无法合作的原因:(github link)
interface SyntheticEvent<T> {
/**
* A reference to the element on which the event listener is registered.
*/
currentTarget: EventTarget & T;
// If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
/**
* A reference to the element from which the event was originally dispatched.
* This might be a child element to the element on which the event listener is registered.
*
* @see currentTarget
*/
target: EventTarget;
// ...
}