我正在尝试使用挂钩将此类组件转换为功能组件
import React, { Component, cloneElement } from 'react';
class Dialog extends Component {
constructor(props) {
super(props);
this.id = uuid();
}
render(){
return ( <div>Hello Dialog</div> );
}
}
该组件以特定的ID启动,因为我可能不得不使用它们的多个实例。如果使用功能组件,该如何实现?
您可以将其存储在以下状态:
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中:
const id = useRef(null);
if(!id.current) {
// initialise
id.current = uuid();
}
// To access it’s value
console.log(id.current);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句