在Reactjs中构建响应组件

时间:2016-12-13 19:20:45

标签: reactjs responsive-design

我正在使用react-responsive module来建立响应式布局。我的渲染函数返回此

<div>
    <Desktop>
        ...
    </Desktop>
    <Phone>
        ...
    </Phone>
</div>

DesktopPhone定义为

export class Phone extends React.Component {
    constructor(props) {
        super(props);
    }

    renderChild(matches) {
        if (matches) {
            return this.props.children
        }

        return null;
    }

    render() {
        return (
            <MediaQuery query="only screen and (min-width : 480px)">
                 {(matches) => (this.renderChild(matches))}
            </MediaQuery>
        )
    }
}

export class Desktop extends React.Component {
    constructor(props) {
        super(props)
    }

    renderChild(matches) {
        if (matches) {
            return this.props.children
        }

        return null;
    }

    render() {
        return (
            <MediaQuery query="only screen and (min-width : 992px)">
                {(matches) => (this.renderChild(matches))}
            </MediaQuery>
        )
    }
}

我遇到的问题是,由于两个查询都匹配,因此组件将呈现为桌面组件中的内容以及手机组件中的内容。我希望它只在桌面匹配时呈现桌面上的内容,以及手机匹配时手机中的内容。有更好的方法吗?

0 个答案:

没有答案