我希望在屏幕大或中或小时自动更改纸张样式。
这里我导入了什么
import React from 'react';
import reactMixin from 'react-mixin';
import ResponsiveMixin from 'react-responsive-mixin';
import Paper from 'material-ui/lib/paper';
我使用ResponsiveMixin来确定屏幕已更改
论文 style = {this.state} 我希望自动更改值。 ,这些值来自componentDidMount()
export class MainLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
height: '100%',
paddingTop: 60,
marginLeft: 258,
marginRight: 6,
paddingLeft: '4%',
paddingRight: '4%'
}
}
componentDidMount() {
this.media({maxWidth: 600}, function () {
/*small*/
this.state = {
height: '100%',
paddingTop: 60,
marginLeft: '3%',
marginRight: '3%',
paddingLeft: '2%',
paddingRight: '2%'
}
}.bind(this));
this.media({minWidth: 601, maxWidth: 1024}, function () {
/*medium*/
this.state = {
height: '100%',
paddingTop: 60,
marginLeft: '3%',
marginRight: '3%',
paddingLeft: '6%',
paddingRight: '6%'
}
}.bind(this));
this.media({minWidth: 1025}, function () {
/*large*/
this.state = {
height: '100%',
paddingTop: 60,
marginLeft: 258,
marginRight: 6,
paddingLeft: '4%',
paddingRight: '4%'
}
}.bind(this));
}
render() {
const {header, content, footer} = this.props; // destructure this.props to consts
return (
<div>
<header>
{header}
</header>
<main>
<Paper style={this.state} zDepth={1}>
{content}
</Paper>
</main>
<footer>
{footer}
</footer>
</div>
)
}
}
reactMixin(MainLayout.prototype, ResponsiveMixin);
非常感谢您的帮助:D非常感谢!
答案 0 :(得分:0)
为什么要将样式存储在组件的状态中? Try this
答案 1 :(得分:0)
componentDidMount()
方法仅在组件输出根据文档呈现到 DOM 后运行一次。因此,如果屏幕尺寸发生变化,则什么都不会发生。 @Material-UI 提供了一个名为 withStyles 的方法,它有助于包装样式并提供一个包含您定义的所有样式的 classes
对象。 withStyles
方法会在屏幕尺寸更改时自动更新。这是示例:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
const styles = theme => ({
paper: { // For extra small screens (phones)
height: '100%',
paddingTop: 60,
marginLeft: '3%',
marginRight: '3%',
paddingLeft: '2%',
paddingRight: '2%',
[theme.breakpoints.up('sm')]: { // For small screens (tablets)
paddingLeft: '6%',
paddingRight: '6%'
},
[theme.breakpoints.up('md')]: { // For medium screens and above
marginLeft: 258,
marginRight: 6,
paddingLeft: '4%',
paddingRight: '4%'
}
}
})
export class MainLayout extends React.Component {
render() {
const {header, content, footer, classes} = this.props; // destructure this.props to consts
return (
<div>
<header>
{header}
</header>
<main>
<Paper className={classes.paper} zDepth={1}>
{content}
</Paper>
</main>
<footer>
{footer}
</footer>
</div>
)
}
}
// That injects `classes` object styles in your component
const YourStyledComponent = withStyles(styles)(MainLayout);
export default YourStyledComponent; // Export or do what you want with the component