简体   繁体   English

停止从 React 中的 select 组件传播

[英]Stop propagation from select component in React

I have a react app which renders a select element within a button.我有一个反应应用程序,它在一个按钮内呈现一个 select 元素。

      <button onClick={this.handleButtonClick}>
        <select value={this.state.value} onChange={this.onChange} >
          <option key={1} value={1}> {"One"} </option>
          <option key={2} value={2}> {"Two"} </option>
        </select>
        "More Text in button, which click should show alert"
      </button>

When the user now tries to select an element from dropdown, the event is propagated to button as well.当用户现在尝试从下拉列表中 select 元素时,该事件也会传播到按钮。 How can I prevent this?我怎样才能防止这种情况?

I've tried following based on other SO posts:我根据其他 SO 帖子尝试过以下操作:


const stopPropagation = (e) => {
  e.nativeEvent.stopPropagation();
  e.nativeEvent.stopImmediatePropagation();
};

onChange = (e) => {
  stopPropagation(e);
  this.setState({ selectValue: e.target.value });
};

Code Link:代码链接:

https://codesandbox.io/s/stop-propagation-in-select-m9f8d?file=/ButtonDropdown.js https://codesandbox.io/s/stop-propagation-in-select-m9f8d?file=/ButtonDropdown.js

You need to add on click to the select that stop the propagation of the on click event您需要将点击添加到 select 以停止点击事件的传播

Therefore add:因此添加:

onClick = (e) => {
  e.stopPropagation();
};
<button onClick={this.handleButtonClick}>
    <select onClick={this.onClick} value={this.state.value} onChange={this.onChange} >
       <option key={1} value={1}> {"One"} </option>
       <option key={2} value={2}> {"Two"} </option>
    </select>
    "More Text in button, which click should show alert"
</button>

Alternative solution: As Sahar Levy rightly suggested, you need onClick for both tags, you can avoid 1 with if condition (ie alert when Button is clicked else do nothing).替代解决方案:正如 Sahar Levy 正确建议的那样,两个标签都需要onClick ,您可以在 if 条件下避免 1(即,单击按钮时发出警报,否则什么也不做)。

onChange = (e) => {
    e.persist();
    this.setState({ value: e.target.value });
};

handleButtonClick = (e) => {
    e.persist();
    if (e.target.tagName === "BUTTON") {
        alert("Button clicked");
    }
};

PS: e.persist() can be removed. PS: e.persist()可以去掉。 To log event data in console, e.persist() helps to display it without any error.要在控制台中记录事件数据, e.persist()有助于在没有任何错误的情况下显示它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM