我有以下 React 组件
const VideoElement = React.createClass({
render() {
return (
<video autoPlay loop muted className="video">
<source src={this.props.source} type="video/mp4" />
</video>
)
}
});
我想得到这个输出,只要 window.innerWidth <= 640
.
我的方法是添加一个初始状态,例如:
getInitialState() {
return { isMobile: window.innerWidth <= 640 }
}
并在 render() 方法中添加一个条件,但如果我尝试访问 this.state.isMobile
给我一个错误:
window is undefined
有人可以解释一下我做错了什么吗?
这是我的方法好吗?
最佳答案
在对 React 组件进行服务器端渲染时,您需要在 life cycle method 中进行 window
检查。 componentDidMount
,仅在客户端调用一次。
在服务器端检查诸如 isMobile
之类的内容时,您应该尝试访问请求来自的代理字符串并将该信息传递给您的客户端。依靠窗口宽度来隐藏/显示内容应该使用 CSS 来完成。
关于javascript - React.js 中的条件加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742135/