Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Native SyntheticEvent合成事件 #14

Open
1uokun opened this issue Jul 16, 2024 · 0 comments
Open

React Native SyntheticEvent合成事件 #14

1uokun opened this issue Jul 16, 2024 · 0 comments
Labels
blog 日常开发笔记

Comments

@1uokun
Copy link
Member

1uokun commented Jul 16, 2024

onStartShouldSetResponder={()=>true}

只有onStartShouldSetResponder返回为true,才会触发onResponderXXX事件,否则不会触发;
缺点是会导致 child 如果不也开启 onStartShouldSetResponder={()=>true}就不能被响应任何事件,包括onScroll

onTouchXXX事件没有这个限制,但是必须是移动端模式,PC模式需要借助hammer-touchemulatornpm包模拟触发。

事件冒泡

停止冒泡事件类型是一一对应的,事件类型不一致时无法阻止。

child onStartShouldSetResponder & onPress 对应 parent onStartShouldSetResponder & onResponderXXX

<View
  onStartShouldSetResponder={() => {
    // not work by child onStartShouldSetResponder true
  }}
  onResponderEnd={() => {
    // not work by child onStartShouldSetResponder true
  }}
  onTouchEnd={()=>{
   // still works
  }}
>
  <View onStartShouldSetResponder={() => true} />
</View>

child onPress

<View
  onStartShouldSetResponder={() => true}
  onResponderEnd={() => {
    // not work by child stopPropagation
  }}>
  <Button
    onPress={(e) => {
      e.stopPropagation()
    }}
    title="btn"
  />
</View>

onTouchEnd 对应 onTouchEnd

<View
  onTouchEnd={() => {
    // not work by stopPropagation
  }}>
  <View
    onTouchEnd={(e) => {
      e.stopPropagation()
    }}
  />
</View>

事件捕获

默认事件冒泡响应顺序是从上到下的,即从target到root的

因此要想先执行root的,可以借助xxxCapture事件捕获

当root的onStartShouldSetResponderCapture返回为true时,child将不响应任何onResponderXXX

<View
  onStartShouldSetResponderCapture={() =>  true}
>
  <View 
    onStartShouldSetResponder={() =>{
        // not work by parent capture
    }}
  />
</View>

同理,当root的onTouchEndCapture执行preventDefault时,child将不响应onTouchEnd

<View
  onTouchEndCapture={(e) => {
      e.preventDefault()
  }}
>
  <View 
    onTouchEnd={() =>{
        // not work by parent preventDefault
    }}
  />
</View>
@1uokun 1uokun added the blog 日常开发笔记 label Jul 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blog 日常开发笔记
Projects
None yet
Development

No branches or pull requests

1 participant