我有一个react组件,当遇到事件(onMouseOver)时,我想调用一个函数。在组件首次出现后,是否可以将eventListener与组件分离? (使用状态是一种解决方案,但我想知道是否还有另一个)
handleOnMouseOver = () => {
console.log('event has occured');
}
render() {
return(
<div onMouseOver={this.handleOnMouseOver}>
);
}
答案 0 :(得分:1)
您可以返回闭包而不污染状态,并保留一个标志,以在第一次出现后禁用监听器。
handleOnMouseOver = () => {
let isActive = true;
return (evt) => {
if(isActive) {
console.log('event has occured');
isActive = false; // disable listener
}
}
render() {
return(
<div onMouseOver={this.handleOnMouseOver()}>
);
}
答案 1 :(得分:1)
您可以在状态中存储一个值,指示您的事件是否已经发生。
如果这样做,您将不会在事件处理程序中返回任何回调函数:
class App extends React.Component {
state = {
hovered: false
}
handleOnMouseOver = () => {
this.setState({ hovered: true })
console.log('event has occured');
}
render() {
return (
<div onMouseOver={!this.state.hovered && this.handleOnMouseOver}>AAAA</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id='root'>