【问题标题】:how to block a react-route based on device dimensions如何根据设备尺寸阻止反应路线
【发布时间】:2018-06-06 19:25:57
【问题描述】:

我有一个响应式响应 Web 应用程序,我需要一个特定的路由,仅适用于移动设备的情况,即设备宽度小于 例如“x”,但所有路由都在同一个文件中创建,例如:

<BrowserRouter>
<Switch>
  <Route exact path='/login/' component={Login} />
  <Redirect exact from='/' to='/login/' />
  <Route exact path='/sample/' component={sample} />
</Switch>

所以现在可以从尺寸大于“x”宽度的设备访问该路线,我如何根据设备宽度使路线可用,或者如何根据设备尺寸阻止特定路线。

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

对于选择性路由,您可以检查您的路由渲染功能。这是一个例子:

class Example extends Component{
    constructor(props){
        super(props);

        this.check = this.check.bind(this);
    }

    check(){
        var w = window,
        d = document,
        e = d.documentElement,
        g = d.getElementsByTagName('body')[0],
        windowWidth = w.innerWidth || e.clientWidth || g.clientWidth; //window width

        return windowWidth > 568; //returns true for widths larger than 568 pixels
    }

    render(){
        return(
            <Router>
                <Route path='/example' render={() => {
                    if(this.check()) return <Child />; 
                    else return <OtherChild />;
                }}/>
            </Router>
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2019-04-27
    • 2018-04-26
    • 1970-01-01
    • 2022-07-19
    相关资源
    最近更新 更多