将类组件ref转换为功能组件useRef钩子

时间:2019-09-30 02:04:55

标签: reactjs react-native react-hooks ref

如何使用useRef将以下类组件语法转换为功能组件?

moveBody = index => {
      this.scrollRef.scrollTo({
        x: index * width,
        animation: false
      })
  }

<ScrollView pagingEnabled ref={node=>this.scrollRef=node}>
 ...
</ScrollView>

1 个答案:

答案 0 :(得分:0)

有关详细信息,请参见React Hooks useRef文档。

const App = () => {
  const scrollRef = React.useRef(null);
  
  const handleClick = () => console.log(scrollRef.current)
  
  return <div ref={scrollRef} onClick={handleClick}>Click Me</div>
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>