react 18.2.0 class函數 refs 代码实列
时间: 2024-05-10 18:14:58 浏览: 14
以下是一个使用 React 18.2.0 和 class 函数组件的代码示例,其中包含使用 refs 的实例:
```
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focus();
}
render() {
return (
<div>
<input type="text" ref={this.textInput} />
</div>
);
}
}
export default MyComponent;
```
在上面的示例中,我们创建了一个名为 `MyComponent` 的 class 函数组件,并在 constructor 中使用 `React.createRef()` 方法来创建一个名为 `textInput` 的 ref 对象。在 `componentDidMount()` 生命周期方法中,我们使用 `this.textInput.current.focus()` 方法来将焦点设置在输入框上。最后,我们在 render 方法中将 ref 对象传递给输入框元素,以便我们可以在其他地方使用它。
当组件挂载时,`componentDidMount()` 方法将被调用,并且我们可以使用 `this.textInput.current` 引用到输入框元素。在这个示例中,我们使用 `focus()` 方法将焦点设置为输入框。
这只是一个简单的示例,但它演示了如何使用 React 18.2.0 中的 class 函数组件和 refs。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)