Detalles del componente: este es un componente de pestaña donde los botones de pestaña se pueden desplazar horizontalmente
Problema: cuando me desplazo horizontalmente y hago clic en un botón de pestaña. El desplazamiento horizontal se restablece. Tal vez todo el contenedor de pestañas se vuelve a representar debido al IDK de setState.
Esperando: quiero poder hacer clic en un botón de pestaña y no actualizar la posición de desplazamiento horizontal del contenedor del botón.
Código actual:
function Tabs(props) { const [tabState, setTabState] = useState(0); const [menuData, setMenuData] = useState('') const TabContainer = styled.div` width: 100%; display: flex; flex-wrap: no-wrap; flex-direction: row; margin: 0 0 20px 0; padding: 20px; align-items: flex-start; justify-content: flex-start; background-color: #fff; overflow-x: auto; const handleTabClick = (index) => { setTabState(index);}return( <> <TabParent> <TabContainer> {props.data && props.data.dataDeets.map((dataDeets,catIndex) => { return ( <TabBtn key={catIndex} onClick={() => handleTabClick(catIndex) } active={tabState === catIndex ? true : false}> {menu.category} </TabBtn> ) }) } </TabContainer> </TabParent> {props.data && props.data.menu.map((menu, catIndex) => { return ( <TabCont key={catIndex} active={tabState === catIndex ? true : false}> <small> {data.categoryDesc} </small> {data.items.map((items, itemIndex) => { return ( <div key={itemIndex} onClick={event => props.openDetails(catIndex, itemIndex, event)}> <ItemCard key={itemIndex} title={items.title} imgurl={items.imgurl} desc={items.desc} price={items.price} /> </div> ) }) } </TabCont> ) }) } </> );
Mi error de novato: espero que esto ayude a otros novatos :)
useState hizo que todo el componente se volviera a renderizar
Mi solución Mover la salida como un componente separado. Esto permite Para mantener su propio estado.