我正在尝试弄清楚如何在移动视图中以不同方式呈现组件(我希望它出现在移动设备的标题之前,但否则出现在之后)
我现在的代码是
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}
);
}
}
然而,这是行不通的(未定义组件),我想我不能只将组件设置为字符串,但希望这足以提供有关正确方法的任何建议的信息
谢谢!
原文由 does_not_compute 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码有几个问题,请参阅评论以获取更多详细信息:
此外,我会将此逻辑移至渲染方法,不使用状态来存储组件而是直接渲染它。例如: