根据屏幕大小以不同的顺序呈现组件(React)
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()
根据分辨率或方向以不同的方式呈现组件-类似于使用媒体查询。
你可以试试:
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;
}
相关文章:
- React重新渲染但未显示正确的组件
- 不能从angular2中的子组件指定父组件中的数组
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- ajax请求的顺序总是不同的
- React组件等待所需道具进行渲染
- 按照选项卡索引的顺序循环一个jQuery选择
- 如何创建带有插槽的vue js组件预加载程序
- KnockoutJS-组件-多个实例
- 匹配一个单词,其中候选人可以跨越顺序组(跨度)
- 如何更改reactjs中外部/独立组件的状态或属性
- 按顺序添加和删除类
- 如何在react js中将值从一个组件发送到另一个组件
- 如何定义组件添加到DataItem的顺序
- 如何在 Vue.js 中保持可排序的数组和组件的顺序
- angularjs组件的执行顺序是什么
- -父组件回调如何通过子道具接收参数顺序/值
- Ember 1.13,在组件中按顺序排列类名
- 根据屏幕大小以不同的顺序呈现组件(React)
- 控制React组件渲染顺序
- 为什么它以随机顺序初始化这个 Knockout.js 组件