简体   繁体   English

React.js 中的条件加载

[英]Conditional loading in React.js

I have the following React Component我有以下 React 组件

const VideoElement = React.createClass({

    render() {
        return (
            <video autoPlay loop muted className="video">
                <source src={this.props.source} type="video/mp4" />
            </video>
        )
    }
});

And I want to have this output just if window.innerWidth <= 640 .我想要这个输出,如果window.innerWidth <= 640

My approach was to add an initial state like:我的方法是添加一个初始状态,如:

getInitialState() {
     return { isMobile: window.innerWidth <= 640 }
}

And add aa condition in the render() method but if I'm trying to access this.state.isMobile trows me an error with:并在 render() 方法中添加 aa 条件,但如果我尝试访问this.state.isMobile则会出现以下错误:

window is undefined窗口未定义

Can someone explain me what I'm doing wrong?有人可以向我解释我做错了什么吗?

It's my approach ok?这是我的方法好吗?

When doing server side rendering of your React components, you need to do your window check from within the life cycle method componentDidMount , which is only invoked once and only on the client.在对 React 组件进行服务器端渲染时,您需要在生命周期方法componentDidMount window检查,该方法仅在客户端调用一次。

When checking things like isMobile on the server side you should try to access what agent string the request came from and pass that information down to your client.在服务器端检查诸如isMobile内容时,您应该尝试访问请求来自哪个代理字符串并将该信息传递给您的客户端。 Relying on window width in order to hide/show content should be done with CSS instead.依靠窗口宽度来隐藏/显示内容应该用 CSS 来完成。

There are better ways to do it, but if that's the case i would do something like this:有更好的方法来做到这一点,但如果是这样的话,我会做这样的事情:

class Hello extends React.Component {

    constructor(props) {
        super(props);
        this.mobile = false;
    }

    componentWillMount(){
        this.mobile = window.innerWidth <= 640
    }

    render() {
        if (this.mobile){
            return (
                <div>Hello Mobile</div>
            );
        }
        else {
            return (
                <div>Hello Desktop</div>
            );
        }
    }
};

ReactDOM.render(
  <Hello/>,
  document.getElementById('app')
);

you can use the operator ternary您可以使用运算符三元

return true ? ():()

for example:例如:

render() {
    return this.mobile ? (
    <di> loading </div>
    ):(
    <di> content custom </div>
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM