react 父组件调用子组件
时间: 2023-09-13 13:06:06 浏览: 161
react 父组件与子组件之间的值传递的方法
在React中,父组件可以通过子组件的实例来调用子组件的方法。有几种方法可以实现这个目的。
方法一:在class组件中使用Refs
在子组件中,可以使用React.createRef()来创建一个ref对象,并将该ref对象作为props传递给父组件。在父组件中,可以通过ref对象来获取子组件的实例,并调用子组件的方法。
例如,在Child.js中:
```javascript
import React, { Component } from 'react';
class Child extends Component {
componentDidMount () {
this.props.onChildEvent(this);
}
sendMessage = () => {
console.log('sending message');
}
render () {
return (
<span>Child</span>
);
}
}
export default Child;
```
在Parent.js中:
```javascript
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
componentDidMount () {
console.log(this.childRef);
}
handleChildEvent = (ref) => {
this.childRef = ref;
}
handleClick = () => {
this.childRef.sendMessage();
}
render () {
return (
<>
<Child onChildEvent={this.handleChildEvent} />
<button onClick={this.handleClick}>Trigger Child Event</button>
</>
);
}
}
export default Parent;
```
方法二:在函数组件中使用useImperativeHandle
在子组件中,可以使用useImperativeHandle hook将子组件的方法暴露给父组件。父组件可以通过子组件的ref来调用子组件的方法。
例如,在Child.js中:
```javascript
import React, { useImperativeHandle } from 'react';
const Child = (props) => {
const sendMessage = () => {
console.log('sending message');
}
useImperativeHandle(props.onRef, () => ({
sendMessage
}));
return <span>Child</span>;
}
export default Child;
```
在Parent.js中:
```javascript
import React, { useRef } from 'react';
import Child from './Child';
const Parent = () => {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.sendMessage();
}
return (
<>
<Child onRef={childRef} />
<button onClick={handleClick}>Trigger Child Event</button>
</>
);
}
export default Parent;
```
以上是两种常见的父组件调用子组件的方法的方式。具体使用哪种方式取决于你的项目需求和个人喜好。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [React 父组件调用子组件中的方法](https://blog.csdn.net/qq_40738077/article/details/119427313)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文