【发布时间】:2017-02-14 07:03:06
【问题描述】:
我想要实现的是通过过渡动画改变不透明度,以获得改变可见元素的平滑效果。
我构建的组件是 Slider。在更改下一张幻灯片的幻灯片不透明度时,当前幻灯片将更改为 1 和 0。
我的第一个 Slide 组件版本
export class Slide extends React.PureComponent {
render() {
let { img, backgroundColor, active, ...props } = this.props;
const Wrapper = styled.div`
background-image: url(${img});
background-color: ${backgroundColor};
background-size: cover;
background-position: 50% 50%;
opacity: ${active ? 1 : 0};
transition: opacity 1s;
`;
return (
<Wrapper/>
)
}
}
我的第一个想法是将当前幻灯片索引存储在状态中。所以我的幻灯片容器知道哪张幻灯片是当前的,并将其活动属性更改为 true。但这会影响重新渲染此幻灯片,并且过渡不可见。第一个问题:为什么?
我最终玩起了 react dom,并手动更改了当前元素的不透明度。
export default class Slider extends Component {
__slidesCount;
__current;
__refs = [];
constructor(props) {
super(props);
this.__current = 0;
this.__slidesCount = this.props.children.length
}
componentWillMount() {
// Save number of slides
}
nextSlide = () => {
let next = this.__current < this.__slidesCount - 1 ? this.__current + 1 : 0,
nextSlide = this.__refs[next],
currentSlide = this.__refs[this.__current];
ReactDOM.findDOMNode(nextSlide).style['opacity'] = 1;
ReactDOM.findDOMNode(currentSlide).style['opacity'] = 0;
this.__current = next;
setTimeout(this.nextSlide, 3000)
};
componentDidMount() {
// set timeout to run it after component mounting is finished
setTimeout(() => {
ReactDOM.findDOMNode(this.__refs[0]).style['opacity'] = 1;
}, 0);
// call function changing slide to next
setTimeout(this.nextSlide, 3000)
}
render() {
let { children, ...props } = this.props;
let slides = children.map((slide, index) => {
return React.cloneElement(slide, { ref: ref => this.__refs.push(ref) })
});
return (
<SlidesWrapper {...props}>
{slides}
</SlidesWrapper>
)
}
}
您如何看待这个解决方案?有什么方法可以更容易吗? 当然,我不想使用 jQuery 并尽量减少外部 css 的使用。
【问题讨论】:
-
你试过 ReactCSSTransitionGroup 吗?
-
我读到的关于
ReactCSSTransitionGroup的内容是它用于新元素或已卸载的元素。ReactCSSTransitionGroup is a high-level API based on ReactTransitionGroup and is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOMfacebook.github.io/react/docs/animation.html
标签: javascript reactjs css-transitions