簡體   English   中英

單擊React中可點擊組件的外部

[英]Click outside of clickable components in React

我有一個基本組件,如下所示。

class List extends React.Component {
  constructor() {
    super(...arguments);
    this.state = {
      selected: null,
      entities: new Map([
        [0, { 'name': 'kot'} ],
        [1, { 'name': 'blini'} ]
      ])
    };
  }
  render() {
    return (<div>
      <ul>{this.renderItems()}</ul>
    </div>)
  }
  renderItems() {
    return Array.from(this.state.entities.entries()).map(s => {
      const [ id, entry ] = s;
      return <li
        key={id}
        onClick={() => this.setState(state => ({ selected: id }))}
        style={{
          color: id === this.state.selected ? 'red' : 'black'
        }}
      >{entry.name}</li>
    })
  }
}

這樣可以讓我點擊任何元素並選擇它。 所選元素將顯示為紅色。 用於輕松編輯的codepen

但是,如果發現的click事件不是這些<li>元素之一,我想要的行為將取消設置任何當前選定的項目。

怎么能在React中完成?

List組件中,您可以添加

  componentDidMount() {
    window.addEventListener("click", (e) => {
      let withinListItems = ReactDOM.findDOMNode(this).contains(e.target);
      if ( ! withinListItems ) {
        this.setState({ selected: null });  
      }
    });
  }

在你的renderItems ,將onClick更改為

onClick={ (e) => {
    // e.stopPropagation();
    this.setState({ selected: id });
  }
}

你可以查看這個codepen http://codepen.io/anon/pen/LRkzWd

編輯:

@kubajz說的是真的,因此我更新了答案。

隨機用戶的答案是正確的,它可能有一個缺陷 - 它依賴於stopPropagation並且有可能某些代碼可能不再按預期工作 - 想象一下在頁面上收集用戶的行為並在某處發送指標 - stopPropagation將阻止冒泡,因此單擊沒有記錄。 另一種方法是檢查在event.target中點擊的內容: http//codepen.io/jaroslav-kubicek/pen/ORXxkL

還有一個很好的實用程序組件,用於監聽文檔級別: react-event-listener

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM