简体   繁体   English

如何让 React 先监听子组件中的事件而不是父组件?

[英]How to make React listen to event in Child component first instead of Parent component?

Consider this example考虑这个例子

<div onClick={() => redirectTo('/foo')}>
  <input type="text"/>
  <input type="button" onClick={() => redirectTo('/bar')} />
</div>;

when i test this example in this case by click to second input , React always redirect to /foo, is that normal behavior and how can i make React redirect to /bar?在这种情况下,当我通过单击第二个输入来测试此示例时,React 总是重定向到 /foo,这是正常行为吗,我该如何让 React 重定向到 /bar? Thanks a lot!非常感谢!

The click event is propagating from the input to the div and both redirects occur.点击事件从输入传播到 div 并且两个重定向都会发生。 You are seeing the result of the last redirect.您正在看到上次重定向的结果。

You can stop the propagation of the input's click event.您可以停止输入的点击事件的传播。

<div onClick={() => redirectTo('/foo')}>
  <input type="text"/>
  <input
    type="button"
    onClick={(e) => {
      e.stopPropagation();
      redirectTo('/bar');
    }}
  />
</div>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Navigation - 在子组件中监听父动作 - React Navigation - Listen parent action in child component 如何允许子组件在父组件之前对路由事件做出反应? - How to allow child component to react to a routing event before the parent component? React:如何监听子组件事件 - React: How to listen to child component events 如何在子组件 ember octane 中监听父组件值的变化? - How to listen parent component value change in child component ember octane? 如何在 React 中将事件从子组件传递到父组件返回到另一个子组件 - how to pass an event from a child component to parent component back down to another child in React 如何将多个事件侦听器从React中的父组件附加到子组件的同一事件中? - How do I attach multiple event listeners to the same event of a child component from its parent component in React? 在父组件中反应子组件 - React child Component in parent Component React hooks 子组件 useEffect 在父组件之前先执行 - React hooks child component useEffect executes first, before parent component 在父组件 React 中未定义子组件中的第一次单击 - First click in child component is undefined in parent component React 在React中取消子组件中父组件的onClick事件 - Cancel onClick event of parent component in child component in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM