Al cambiar el tamaño, incluso el oyente no se activa.
class MainContainer extends React.Component { constructor(props) { super(props); this.containerRef = React.createRef(); this.state = {}; } componentDidMount() { this.containerRef.current.addEventListener("resize", this.handleResize); } componentWillUnmount() { this.containerRef.current.removeEventListener("resize", this.handleResize); } handleResize() { console.log("handleResize"); } render() { return ( <React.Fragment> <Container ref={this.containerRef}> <Body /> </Container> <ShadowTop show={this.state.top} /> </React.Fragment> ); } }--
export const Container = styled.div` @media (max-width: 760px) { position: absolute; } margin-top: ${({ theme }) => theme.header.height.percent}%; margin-top: -webkit-calc(${({ theme }) => theme.header.height.pixel}px); margin-top: -moz-calc(${({ theme }) => theme.header.height.pixel}px); margin-top: calc(${({ theme }) => theme.header.height.pixel}px); height: ${({ theme }) => Math.abs(100 - theme.header.height.percent)}%; height: -webkit-calc(100% - ${({ theme }) => theme.header.height.pixel}px); height: -moz-calc(100% - ${({ theme }) => theme.header.height.pixel}px); height: calc(100% - ${({ theme }) => theme.header.height.pixel}px); position: fixed; float: none; clear: both; top: 0; right: 0; width: ${({ theme }) => 100 - theme.sidebar.width.percent}%; width: -webkit-calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px); width: -moz-calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px); width: calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px); z-index: 2; pointer-events: auto; overflow: auto; `;¿Qué estoy haciendo mal aquí?
Estoy tratando de detectar cuándo el div , también conocido como Container , un elemento styled-components ha cambiado de tamaño.
El evento de cambio de resize se activa en window , no en elementos individuales. Esto se debe a que el evento de cambio de resize está diseñado para manejar el cambio de tamaño de la ventana gráfica, no el cambio de tamaño del contenido. Para detectar cambios en el tamaño del contenido, puede usarResizeObserver .
Hay muchas maneras de incorporar esto en su proyecto React. Aquí hay un ejemplo similar a lo que tienes en la pregunta:
class MainContainer extends React.Component { constructor(props) { super(props); this.ulRef = React.createRef(); this.state = { item: "", todoList: [] }; // Binding methods to the current intance is only needed if you pass // the method as an argument to another function and want acces to the // `this` keyword in the method. this.handleResize = this.handleResize.bind(this); this.addTodoItem = this.addTodoItem.bind(this); } componentDidMount() { this.ulObserver = new ResizeObserver(this.handleResize); this.ulObserver.observe(this.ulRef.current); } componentWillUnmount() { this.ulObserver.disconnect(); } handleResize(entries) { console.log("handleResize"); console.log(entries); } addTodoItem(event) { event.preventDefault(); this.setState((state) => ({ todoList: [...state.todoList, state.item], item: "", })); } render() { return ( <div> <form onSubmit={this.addTodoItem}> <input value={this.state.item} onChange={e => this.setState({ item: e.target.value })} /> <button type="submit">add</button> (or press <kbd>Enter</kbd>) </form> <ul ref={this.ulRef}> {this.state.todoList.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> </div> ); } } ReactDOM.render(<MainContainer />, document.querySelector("#root")); <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div> También puede haber bibliotecas que lo ayuden a combinar ResizeObserver y React. Pero no está de más entender lo que está sucediendo debajo del capó.
los eventos de cambio de tamaño solo se activan en el objeto de la ventana
Puede leer más sobre el evento de cambio de tamaño
Debería ser:
componentDidMount() { window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); } Puede agregar rebote a debounce para hacerlo con menos frecuencia.