我正在尝试使我的轮播高度在更改时动态调整大小。但是我似乎无法单纯从孩子的身高变化中引发状态变化。
听孩子们很好,实际上我不确定为什么它不起作用。
将错误消息附加到轮播中的孩子时,会发生问题。它不会更新。
目前我所知道要做的最好的事情是间隔... 有更好的方法吗?
import React,{useState,useEffect,useRef} from 'react';
import './Carousel.scss';
// Wrapped children components must be placed inside of <div> elements
const Carousel = ({slideTo,children}) => {
const [carouselStyle,setCarouselStyle] = useState({});
const activeRef = useRef(null);
const index = slideTo - 1
const newChildren = [];
children.map((d,i) => {
let addClass = (d.props.classname !== undefined) ? d.props.classname: ""
const newProps = {
key: i
};
if(i === index){
addClass += " active"
newProps.ref = activeRef;
}
newProps.classname = addClass.trim();
const newChild = React.cloneElement(d,newProps);
newChildren.push(newChild);
return false
});
const carouselContainerStyle = {
left: (((slideTo * 100) - 100) * -1) + "%",width: (newChildren.length * 100)+ "%"
}
useEffect(() => {
const interval = setInterval(function(){
console.log("int");
if(activeRef != null){
if(carouselStyle.height === undefined || carouselStyle.height !== activeRef.current.clientHeight){
setCarouselStyle({
height: activeRef.current.clientHeight,});
}
}
},50)
return () => {
clearInterval(interval)
}
},[]);
useEffect(() => {
console.log("children update");
if(activeRef.current !== null){
setCarouselStyle({
height: activeRef.current.clientHeight,});
}
},[slideTo,children]);
return (
<div classname="carousel" style={carouselStyle}>
<div style={carouselContainerStyle} classname="carousel-container">
{newChildren}
</div>
</div>
);
};
export default Carousel;
实施
<Carousel slideTo={slide}>
<div><SignIn/></div>
<div><SignUp/></div>
</Carousel>