使用钩子将类组件转换为功能组件 [英] Convert class component to functional components using hooks
本文介绍了使用钩子将类组件转换为功能组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用钩子将此类组件转换为功能组件
I am trying to convert this class component to functional component using hooks
import React, { Component, cloneElement } from 'react';
class Dialog extends Component {
constructor(props) {
super(props);
this.id = uuid();
}
render(){
return ( <div>Hello Dialog</div> );
}
}
这个组件是用一个特定的 ID 启动的,因为我可能不得不使用它们的多个实例.如果我使用功能组件,我该如何实现?
This component is initiated with a specific ID because I may have to use multiple instances of them. How can I achieve this if I use functional component?
推荐答案
您可以将其存储在状态:
You may store it in state:
const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation
// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation
您也可以将其存储在 React ref 中:
You may also store it in React ref:
const id = useRef(null);
if(!id.current) {
// initialise
id.current = uuid();
}
// To access it’s value
console.log(id.current);
这篇关于使用钩子将类组件转换为功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文