问题
My styled components theme currently includes:
const breakpoints = {
medium: '640px',
large: '1080px',
};
const MyContainer = styled.div`
// Default mobile stylings
${({ theme }) => theme.media.medium`
// CSS goes here
`}
${({ theme }) => theme.media.large`
// CSS goes here
`}
`;
In my react component, I need an onClick handler for an item but ONLY when the breakpoint is small, not medium or large.
In my react component, for some reason, I can not figure this out...
const MyC = class extends React.Component {
render() {
console.log(this.props.theme);
....
}
};
While using Styled Components to handle breakpoints, how can I inform my React Component if the current breakpoint is currently size small and to only then use an onClick handler?
回答1:
You need to handle this with javascript. Add this to your component:
isEnabled = true;
calcButtonState = () => {
if(window.innerWidth < breakpoints.medium) {
this.isEnabled = false;
} else {
this.isEnabled = true;
}
}
handleButtonClick = () => {
if(this.isEnabled === false) {
return;
}
}
componentDidMount() {
this.calcButtonState();
window.addEventListener('resize', this.calcButtonState);
}
componentWillUnmount() {
window.removeEventListener('resize', this.calcButtonState);
}
What this basically does is set a boolean to true, if your window with is larger than medium, and if it is smaller, set it to false. You click handler will then check for this boolean. If it is false, it will return immediately.
Please also use some sort of debounce function here for the resize event.
来源:https://stackoverflow.com/questions/50009139/with-styled-components-how-to-only-apply-a-style-to-small-devices