我正在创建一个带有react的简单轮播,我注意到索引被多次调用,我不明白为什么,这是我的代码段,这里也是完整版本https://codesandbox.io/s/small-bash-4l7ix?file=/src/index.js
...
const pages = [
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightpink' }}>
A
</animated.div>
)),
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightblue' }}>
B
</animated.div>
)),
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightgreen' }}>
C
</animated.div>
)),
]
export default function App() {
const [index, set] = useState(0)
const [containerRef, containerSize] = useDimensions()
const transitions = useTransition(index, p => p, {
from: { opacity: 0, transform: 'translate3d(100%,0,0)' },
enter: { opacity: 1, transform: 'translate3d(0%,0,0)' },
leave: { opacity: 0, transform: 'translate3d(-50%,0,0)' },
})
const divStyle = {
height: `${containerSize.height}px`,
}
console.log(index)
return (
<>
<button className={`btn ${index === 0 ? 'btn--active' : ''}`} onClick={() => set(0)}>
Slide 1
</button>
<button className={`btn ${index === 1 ? 'btn--active' : ''}`} onClick={() => set(1)}>
Slide 2
</button>
<button className={`btn ${index === 2 ? 'btn--active' : ''}`} onClick={() => set(2)}>
Slide 3
</button>
<div style={divStyle} className="simple-trans-main">
{transitions.map(({ item, props, key }) => {
const Page = pages[item]
return <Page ref={containerRef} key={key} style={props} />
})}
</div>
<p> Lorem ipusum</p>
</>
)
}
...
答案 0 :(得分:2)
答案 1 :(得分:2)