簡體   English   中英

反應自定義合成事件

[英]React custom synthetic event

我想創建一個自定義合成事件,以便我可以根據配置選項有條件地附加處理程序(觸摸啟動或單擊)但是,我似乎無法找到有關如何完成此操作的任何信息理想情況下我希望下面(onTap 屬性)

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

然后 onTap 會在 touchstart 或 click 或我在配置中定義的任何事件上附加處理程序

這可能嗎? 是否可以定義一個將掛在每個組件上的自定義屬性?

問候

你可以嘗試這樣的事情:

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

警告:我不保證這是否有效。 這可能是一個非常糟糕的主意,並且應該在一個庫中使用。

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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM