Евг*_*зов 4 reactjs conditional-rendering responsive
有一个问题,我不知道如何在技术上正确地实现该组件。我想根据设备屏幕对元素进行条件渲染。示例:如果屏幕小于 700 px,则我得出一个结论,如果大于,则得出第二个结论
if(window.innerWidth > 700) {
return(
<Content>
1
</Content>)
};
return (
<Content>
2
</Content>)
Run Code Online (Sandbox Code Playgroud)
我使用react、next js和typeScript技术
这个怎么做?
gli*_*a93 15
在组件中创建宽度状态,并在窗口调整大小事件上更新状态,如下所示:
const App = () => {
const [width, setWidth] = React.useState(window.innerWidth);
const breakpoint = 700;
React.useEffect(() => {
const handleResizeWindow = () => setWidth(window.innerWidth);
// subscribe to window resize event "onComponentDidMount"
window.addEventListener("resize", handleResizeWindow);
return () => {
// unsubscribe "onComponentDestroy"
window.removeEventListener("resize", handleResizeWindow);
};
}, []);
if (width > breakpoint) {
return (
<div>
<h3>Component 1</h3>
<p>Current width is {width} px</p>
</div>
);
}
return (
<div>
<h3>Component 2</h3>
<p>Current width is {width} px</p>
</div>
);
}
class Root extends React.Component {
render() {
return (
<App/>
);
}
}
ReactDOM.render(<Root />, document.getElementById('root'));Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root">
</div>Run Code Online (Sandbox Code Playgroud)