我有:
class SomeComponent extends Component {
state = {
outside: false,
inside: false,
}
onOutsideClick = () => this.setState({ outside: true })
onInsideClick = () => this.setState({ inside: true })
render() {
return (<div onClick={this.onOutsideClick}>Some text, <p onClick={this.onInsideClick}>some other text</p></div>)
}
}
当我点击一些其他文本时,onOutsideClick
处理程序也会触发,因此this.state.outside
将更改为真的。如果点击其他文本,我不想触发任何其他方法。
我尝试在 onOutsideClick
中使用 e.stopPropagation
和 if (this.state.inside) return
但这些都不起作用
最佳答案
您应该使用event.stopPropagation()
来停止冒泡事件。很难说为什么 stopPropagation()
对您不起作用。
使用 stopPropagation()
进行工作演示:https://codesandbox.io/s/wpPJ1LkXR
import React, { Component } from 'react';
import { render } from 'react-dom';
const INSIDE_CLICK = 'inside';
const OUTSIDE_CLICK = 'outside';
class App extends Component {
state = {
clicked: undefined,
};
onOutsideClick = () => {
this.setState({ clicked: OUTSIDE_CLICK });
};
onInsideClick = (event) => {
event.stopPropagation();
this.setState({ clicked: INSIDE_CLICK });
};
render() {
return (
<div onClick={this.onOutsideClick}>
Some text, <p onClick={this.onInsideClick}>some other text</p>
<div style={{ border: '2px solid red' }}>
Clicked: {this.state.clicked}
</div>
</div>
);
}
}
render(<App />, document.getElementById('root'));
关于javascript - 防止React中的setState触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45020700/