gpt4 book ai didi

javascript - react 自定义合成事件

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:56 24 4
gpt4 key购买 nike

我想创建一个自定义合成事件,以便我可以根据配置选项有条件地附加处理程序(触摸启动或单击)但是,我似乎找不到任何有关如何做到这一点的信息理想情况下,我想要以下内容(onTap 属性)

<Button onTap={someHandler} title="Register" />

然后 onTap 会在 touchstart 或 click 或我在配置中定义的任何事件上附加处理程序

这可能吗?是否可以定义一个 Hook 每个组件的自定义属性?

问候

最佳答案

你可以尝试这样的事情:

const W = (() => {
// all elements supported by React
const names = 'a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|menu|menuitem|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr|circle|clipPath|defs|ellipse|g|image|line|linearGradient|mask|path|pattern|polygon|polyline|radialGradient|rect|stop|svg|text|tspan'.split('|')
const res = {}
for (const El of names) {
res[El] = ({ onTap, ...props }) => {
onTap = onTap || x=>x
props.onClick = props.onClick || x => x
props.onTouchStart = props.onTouchStart || x => x
<El {...props} onClick={(...args) => {onTap(...args); props.onClick(...args)} onTouchStart={(...args) => {onTap(...args); props.onTouchStart(...args)} />
}
}
return res;
})()

<W.button onTap={() => alert('hi')} />

这会将 onTap 处理程序添加到任何元素的 onClickonTouchStart 事件中。

类似的技术可用于包装复合组件。

<小时/>

要包装每个组件,您需要包装React.createElement

Warning: I make no guarantees about if this will work. It is probably a very bad idea, and should not be used in a library.

const _ce = React.createElement.bind(React)
React.createElement = (name, props, ...args) => {
if (!props) {
return _ce(name, props, ...args)
}
const { onTap, ...newProps } = props
if (onTap) {
if (props.onClick) {
newProps.onClick = (...args) => {
props.onClick(...args)
onTap(...args)
}
} else {
newProps.onClick = onTap
}
if (props.onTouchStart) {
newProps.onTouchStart = (...args) => {
props.onTouchStart(...args)
onTap(...args)
}
} else {
newProps.onTouchStart = onTap
}
}
return _ce(name, newProps, ...args)
}

关于javascript - react 自定义合成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com