react 點擊空白處隱藏彈出層
阿新 • • 發佈:2017-09-27
truct cli 元素 ext str opp hang 點擊事件 ren
點擊空白處隱藏彈出層的原理是:在 document 上綁定事件來隱藏彈出層,這樣點擊任何元素的時候都會冒泡到 document 上,都會執行隱藏彈出層的功能。然後我們在不需要隱藏彈出層的元素上阻止冒泡即可。
class Select extends Component { constructor(props) { super(props); this.state = { selected: props.list[0], showList: false }; this.showList = this.showList.bind(this); } componentDidMount() { // 在 document 上綁定點擊事件,隱藏彈出層 document.addEventListener(‘click‘, (e) => { this.setState({ showList: false }); }); } showList(e) { // 使用 react 的 e.stopPropagation 不能阻止冒泡,需要使用 e.nativeEvent.stopImmediatePropagation,這裏我們對其進行封裝,方便多次調用this.stopPropagation(e); this.setState({ showList: !this.state.showList }); } selectList(i) { const selected = this.props.list[i]; this.setState({ selected: selected, showList: false }); this.props.onChange(selected); }// 封裝後的阻止冒泡功能 stopPropagation(e) { e.nativeEvent.stopImmediatePropagation(); } render() { const { list } = this.props; const { selected, showList } = this.state; return ( <div className="hp-select"> <span className="hp-select__text">{selected.text}</span> <span className="hp-select__btn" onClick={this.showList}></span> <div className="hp-select__list" style={{ display: showList ? ‘block‘ : ‘none‘ }} // 方便的調用封裝冒泡功能來阻止冒泡 onClick={this.stopPropagation} > <ul> { list && list.map((item, i) => { return <li key={item.value} onClick={this.selectList.bind(this, i)}>{item.text}</li>; }) } </ul> </div> </div> ); } }
react 點擊空白處隱藏彈出層