gpt4 book ai didi

javascript - 如何避免 React 组件上的 onclick 函数冲突

转载 作者:行者123 更新时间:2023-11-29 17:41:20 25 4
gpt4 key购买 nike

我有一个下面的组件:当我单击整个 div 时,有 2 个用例当我单击 <img> 时,会执行某些功能,执行一些函数。我定义了 2 个 Prop ,onClick ,当单击整个 div 时和onIconClick当点击图片时。

export default class List extends React.Component {
onClick() {
this.props.onClick();
}
onIconClick() {
this.props.onIconClick();
}
render() {
return (
<div style="width:200px, height: 200px" onClick={this.onClick.bind(this)}>
<img src="delete.png" onClick={this.onIconClick.bind(this)} />
</div>
);
}
}

这是我调用组件的方式:

export default class MyApp extends React.Component {
onClick() {
//some execution
}
onIconClick() {
//some other execution
}
render() {
return (
<List
onClick={this.onClick.bind(this)}
onIconClick={this.onIconClick.bind(this)}
/>
);
}
}

现在我的问题是 this.onClick.bind(this)即使我单击图像,它也会一直被调用,因此我永远不会到达 this.onIconClick.bind(this) .

我尝试颠倒顺序:

 <List onIconClick={this.onIconClick.bind(this)} onClick={this.onClick.bind(this)} />

仍然不起作用,不确定应该使用什么选择标准来区分这两次点击。

有什么想法吗?

最佳答案

试试这个:

class Parent extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.onIconClick = this.onIconClick.bind(this);
}
onClick() {
alert("Parent-onClick()");
}
onIconClick() {
alert("Parent-onIconClick()");
}
render() {
return (
<div>
<Child onClick={this.onClick} onIconClick={this.onIconClick} />
</div>
);
}
}

class Child extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.onIconClick = this.onIconClick.bind(this);
}
onClick() {
this.props.onClick();
}
onIconClick(e) {
e.stopPropagation();
this.props.onIconClick();
}
render() {
let styles = {
height: "500px",
backgroundColor: "blue",
paddingTop: "20px"
};
return (
<div onClick={this.onClick} className="img-wrapper" style={styles}>
<img
onClick={this.onIconClick}
src="https://via.placeholder.com/350x150"
alt="img"
/>
</div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>

这个想法是使用 SyntheticEventstopPropagation() 方法实例。


Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it.


使用SyntheticEvent的方法允许我们的代码在所有浏览器中表现完全相同。

关于javascript - 如何避免 React 组件上的 onclick 函数冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52939515/

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