三元反应的侧边栏

时间:2019-03-13 19:45:26

标签: javascript reactjs

我有一个带有sidebarOpen道具的补充工具栏组件,即:<SidebarWrapper sidebarOpen={this.props.sidebarOpen}>

我还有一个按钮,其中onClicksidebarOpen切换为true和false。

我还有一个事件侦听器,在移动设备中时,请将sideBarOpen设置为false。这是函数:

setSidebar = () => {
 const isMobile = (typeof window !== 'undefined') && (window.innerWidth < 500)

 if(isMobile) {
   this.props.openSidebar(false)
 } else {
   this.props.openSidebar(true)
 }
}

我要完成的工作是,如果您在移动设备上单击按钮并调整屏幕大小,则侧边栏应保持打开状态而不会闪烁。

Video Here

这里是完整的组件:

import React from 'react'

import { bindActionCreators } from 'redux'
import { toggleDarkTheme, openSidebar } from '../../actions/layout'
import { connect } from 'react-redux'
import {SidebarWrapper} from './styles'


const mapDispatchToProps = dispatch => {
  return {
    toggleDarkTheme: bindActionCreators(toggleDarkTheme, dispatch),
    openSidebar: bindActionCreators(openSidebar, dispatch)
  }
}

const mapStateToProps = state => ({ sidebarOpen: state.layout.sidebarOpen });

export default connect(mapStateToProps, mapDispatchToProps)(class Sidebar extends React.Component {

  setSidebar = () => {
    const isMobile = (typeof window !== 'undefined') && (window.innerWidth < 500)

    if(isMobile) {
      this.props.openSidebar(false)
    } else {
      this.props.openSidebar(true)
    }
  }

  componentDidMount() {
    window.addEventListener("resize", this.setSidebar);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.setSidebar);
  }

  render() {
    return (
      <SidebarWrapper sidebarOpen={this.props.sidebarOpen}>
          <button onClick={this.props.toggleDarkTheme}>Darkness</button>
      </SidebarWrapper>
    )
  }
})

和样式:

import styled from 'styled-components'
import breakpoint from 'styled-components-breakpoint'

export const SidebarWrapper = styled.div`
  display: ${props => props.sidebarOpen ? 'flex' : 'none'};
  flex-direction: column;

`

0 个答案:

没有答案