直接回答:组件自适应宽高要拿到父容器的真实尺寸:挂载后用 ref 测量,再监听变化重新渲染;监听 window 的 resize 覆盖不到容器自身变化,更稳妥的是 ResizeObserver。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
width: props.width || -1,
height: props.height || -1,
}
}

componentDidMount() {
this.updateSize();
window.addEventListener('resize', () => this.updateSize());
}

componentWillUnmount() {
window.removeEventListener('resize', () => this.updateSize());
}

updateSize() {
try {
const parentDom = ReactDOM.findDOMNode(this).parentNode;
let { width, height } = this.props;
//如果props没有指定height和width就自适应
if (!width) {
width = parentDom.offsetWidth;
}
if (!height) {
height = width * 0.38;
}
this.setState({ width, height });
} catch (ignore) {
}
}

render() {
return (
<div className="test" style={ { width: this.state.width, height: this.state.height } }>
{`${this.state.width} x ${this.state.height}`}
</div>
);
}
}

ReactDOM.render(
<Card/>,
document.getElementById('root')
);

这篇笔记整理自我自己的实践记录,如果做法有出入,或者你踩过别的坑,欢迎到留言板一起聊聊。

站内搜索

没有找到内容!