我是React的新手,我正在尝试将下面的代码转换为函数组件,但它不起作用,我从未使用过类组件。有人能帮我转换一下吗?提前谢谢。
import React from 'react'
import ReactDOM from 'react-dom'
import ScrollSnap from 'scroll-snap'
import './styles.css'
class App extends React.Component {
container = React.createRef()
bindScrollSnap() {
const element = this.container.current
new ScrollSnap(element, {
snapDestinationY: '90%',
}).bind()
}
componentDidMount() {
this.bindScrollSnap()
}
render() {
return (
<div ref={this.container}>
</div>
)
}发布于 2021-12-02 11:37:31
下面是你需要做的:
createRef替换为useRef,后者是在functional components.componentDidMount中使用的函数钩子。将useEffect()替换为空数组作为依赖数组,这基本上是在挂载时运行一次该代码。
const App = () => {
const containerRef = React.useRef(null);
const bindScrollSnap = () => {
new ScrollSnap(containerRef , {
snapDestinationY: '90%',
}).bind()
}
React.useEffect(() => {
bindScrollSnap();
}, []);
return <div ref={containerRef}></div>
}https://stackoverflow.com/questions/70198595
复制相似问题