Javascript 当我在父组件中单击时,如何使用e.stopPropagation事件?
如何确保在react中单击子组件时不会在父组件中触发单击 我正在尝试使用e.stopPropagation,但当我单击它时,我看到此错误 TypeError:e.StopperPogation不是一个函数 为什么会这样Javascript 当我在父组件中单击时,如何使用e.stopPropagation事件?,javascript,reactjs,Javascript,Reactjs,如何确保在react中单击子组件时不会在父组件中触发单击 我正在尝试使用e.stopPropagation,但当我单击它时,我看到此错误 TypeError:e.StopperPogation不是一个函数 为什么会这样 class ModuleGroup extends React.Component { constructor(props) { super(props); this.toggleHidden = this.toggleHidden.bind(this);
class ModuleGroup extends React.Component {
constructor(props) {
super(props);
this.toggleHidden = this.toggleHidden.bind(this);
this.handleClick = this.handleClick.bind(this);
this.state = {
isVisible: false,
};
}
toggleHidden() {
this.setState({
isVisible: !this.state.isVisible,
});
}
handleClick(e) {
// console.log("e.Target", e.currentTarget.textContent);
console.log("e.Target", e);
e.stopPropagation();
}
render() {
return (
<div
onClick={(e) => this.handleClick(this.props.id)}
// onClick={this.handleClick}
className="moduleGroup"
onMouseEnter={this.toggleHidden}
onMouseLeave={this.toggleHidden}
>
{this.props.id}
<div
value={this.props.id}
className={`modulesSet ${this.state.isVisible && "visible"}`}
>
{this.props.modules &&
this.props.modules.map((module) => (
<Module key={module.key} id={module.key} />
))}
</div>
</div>
);
}
}
在onClick={e=>this.handleClickthis.props.id}中,传递的是id,而不是e
考虑这个.handleclick,而不是这个.props.id
因此,您的处理程序看起来像:
handleClick(e, id) {}
您是否尝试过:
onClick={(e) => this.handleClick(e, this.props.id)}
handleClick(e, id) {
// console.log("e.Target", e.currentTarget.textContent);
console.log("e.Target", e);
e.stopPropagation(); // Or e.preventDefault();
}
成功了,谢谢@光盘