我有一个带有sidebarOpen
道具的补充工具栏组件,即:<SidebarWrapper sidebarOpen={this.props.sidebarOpen}>
我还有一个按钮,其中onClick
将sidebarOpen
切换为true和false。
我还有一个事件侦听器,在移动设备中时,请将sideBarOpen
设置为false。这是函数:
setSidebar = () => {
const isMobile = (typeof window !== 'undefined') && (window.innerWidth < 500)
if(isMobile) {
this.props.openSidebar(false)
} else {
this.props.openSidebar(true)
}
}
我要完成的工作是,如果您在移动设备上单击按钮并调整屏幕大小,则侧边栏应保持打开状态而不会闪烁。
这里是完整的组件:
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;
`