父组件通过ref调用子组件的接口方法获取到子组件的值
时间: 2023-08-18 22:11:20 浏览: 42
父组件可以通过 `ref` 获取到子组件的实例,然后调用子组件的方法来获取值。下面是一个示例:
```jsx
import React, { Component } from 'react';
class ChildComponent extends Component {
getValue() {
return '子组件的值';
}
render() {
return <div>子组件</div>;
}
}
class ParentComponent extends Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
handleClick = () => {
const childComponent = this.childRef.current;
const value = childComponent.getValue();
console.log(value); // 输出子组件的值
};
render() {
return (
<div>
<ChildComponent ref={this.childRef} />
<button onClick={this.handleClick}>获取子组件的值</button>
</div>
);
}
}
```
在上面的示例中,父组件 `ParentComponent` 使用 `React.createRef()` 创建了一个 `childRef` 引用,然后将其传递给子组件 `ChildComponent` 的 `ref` 属性。在父组件的 `handleClick` 方法中,通过 `this.childRef.current` 获取到子组件的实例,然后调用 `getValue` 方法获取到子组件的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)