react 移动端像素大小配置
叶江怀 2019-06-14 mobilereact
# react移动端自适应px大小
css
@function px2rem($n) {
@return #{$n/(750 * 16 / 320)}rem;
}
1
2
3
2
3
js
const setHtmlFont = function() {
const docEl = document.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
const { clientWidth } = docEl;
if (!clientWidth) return;
docEl.style.fontSize = `${16 * (clientWidth / 320)}px`;
};
if (!document.addEventListener) return;
docEl.style.fontSize = `${16 * (docEl.clientWidth / 320)}px`;
window.addEventListener(resizeEvt, recalc, false);
document.addEventListener('DOMContentLoaded', recalc, false);
};
export default class demo extends React.Component {
state={
...
}
componentDidMount() {
setHtmlFont();
}
componentWillUnmount() {
document.querySelectorAll('html')[0].style.fontSize = '';
}
render(){
...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34