将React函数组件转换为React类组件

时间:2020-07-27 12:19:28

标签: reactjs

我有一个使用useState设置了引用的代码,但我想将代码转换为类组件

  const [imageSliderRef, setImageSliderRef] = useState(null);
  const [textSliderRef, setTextSliderRef] = useState(null);

针对上述内容并在jsx中呈现

The code with the hooks and jsx

1 个答案:

答案 0 :(得分:1)

如果要使用类,则可以使用React.createRef()创建引用,并通过ref属性将引用附加到React元素。构造组件时,通常将引用分配给实例属性,以便可以在整个组件中对其进行引用。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}