[英]Render component in different order depending on screen-size (React)
我正在尝试弄清楚如何在移动视图中以不同的方式呈现组件(我希望它出现在移动端的标题之前,否则之后)
我现在的代码是
import React from 'react';
import NavigationBar from './NavigationBar';
import SiteHeader from './SiteHeader';
export default class App extends Component {
constructor(props) {
super(props);
let width = window.innerWidth;
if (width > 768) {
this.setState(renderComponent =
`<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>`
);
} else {
this.setState(renderComponent =
`<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>`
);
}
}
render() {
return (
{renderComponent}
);
}
}
但是这不起作用(未定义组件),我想我不能只将组件设置为字符串,但希望这足以提供有关正确方法的任何建议的信息
谢谢!
您的代码有几个问题,有关更多详细信息,请参阅注释:
export default class App extends Component {
constructor(props) {
super(props);
// typo: use `=` instead of `:`
let width = window.innerWidth;
// dont use setState in constructor, initialize state instead
this.state = {};
if (width > 768) {
// set renderComponent property according to window size
// components are declared using JSX, not string (do not use ``)
this.state.renderComponent = (
<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>
);
} else {
this.state.renderComponent = (
<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>
);
}
}
render() {
// access state through `this.state`
// you don't need {} while it is not inside JSX
return this.state.renderComponent;
}
}
此外,我会将这个逻辑移到渲染方法中,不要使用状态来存储组件,而是直接渲染它。 例如:
export default class App extends Component {
render() {
let width = window.innerWidth;
if (width > 768) {
return (
<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>
);
} else {
return (
<div className="container">
<NavigationBar />
<SiteHeader />
{this.props.children}
</div>
);
}
}
}
我认为你应该在render()
方法中有你的渲染逻辑。 您可以使用matchMedia()
根据分辨率或方向以不同方式呈现组件 - 与使用媒体查询时类似。
https://developer.mozilla.org/pl/docs/Web/API/Window/matchMedia
你可以试试这个:
componentWillMount = () => {
let mql = window.matchMedia("all and (max-width: 767px)")
if (mql.matches) { // if media query matches
document.body.style.backgroundColor = "#fff";
} else {
document.body.style.backgroundColor = "#2d74da";
}
}
componentWillUnmount = () => {
document.body.style.backgroundColor = null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.