【问题标题】:how to convert class component to function component?如何将类组件转换为功能组件?
【发布时间】:2022-01-08 21:27:22
【问题描述】:

我是 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>
 )
}

【问题讨论】:

    标签: reactjs react-class-based-component scroll-snap


    【解决方案1】:

    这是你需要做的:

    1. createRef 替换为useRef,这是要在功能组件中使用的功能挂钩。
    2. 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>
    }
    

    【讨论】:

    • TypeError: this.listenerElement.addEventListener is not a function 给出了与我尝试转换它时完全相同的错误。这是整个代码:` const containerRef = React.useRef(null); const bindScrollSnap = () => { new ScrollSnap(containerRef, { snapDestinationY: "90%", }).bind(); }; React.useEffect(() => { bindScrollSnap(); }, []); return (
      ); };导出默认应用程序; `
    • scroll-snap 期望元素不是参考。尝试找到与 react 一起使用的其他库
    • 是的,我找到了另一个库。还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2020-08-26
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多