我正在尝试弄清楚如何在移动 View 中以不同方式呈现组件(我希望它出现在移动设备的标题之前,但否则出现在之后)
我现在的代码是
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>
);
}
}
}
关于javascript - 根据屏幕大小(React)以不同顺序渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235506/