防止React中的setState触发器

时间:2017-07-10 20:06:54

标签: javascript reactjs javascript-events

我有:

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>)
  }
}

当我点击some other text时,onOutsideClick处理程序也会触发,因此this.state.outside将更改为true。如果单击some other text,我不想触发任何其他方法。

我在e.stopPropagation中使用if (this.state.inside) returnonOutsideClick进行了尝试,但没有一个有效

干杯!

2 个答案:

答案 0 :(得分:1)

您应该使用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'));

答案 1 :(得分:0)

在调用setState之前检查一些布尔值,并在setState回调中再次将其置为false。