react18父组件调用子组件的方法
时间: 2023-10-13 10:21:44 浏览: 41
React中父组件调用子组件的方法有多种方法,以下是其中两种:
1. 使用ref引用子组件,然后通过ref调用子组件的方法。示例代码如下:
```jsx
class Parent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
handleChildMethod() {
this.childRef.current.childMethod();
}
render() {
return (
<div>
<Child ref={this.childRef} />
<button onClick={() => this.handleChildMethod()}>调用子组件方法</button>
</div>
);
}
}
class Child extends React.Component {
childMethod() {
console.log("子组件方法被调用了!");
}
render() {
return <div>子组件</div>;
}
}
```
2. 将父组件方法通过props传递给子组件,在子组件中调用该方法。示例代码如下:
```jsx
class Parent extends React.Component {
handleChildMethod() {
console.log("父组件方法被调用了!");
}
render() {
return (
<div>
<Child onChildClick={() => this.handleChildMethod()} />
</div>
);
}
}
class Child extends React.Component {
handleClick() {
this.props.onChildClick();
}
render() {
return (
<div>
子组件<button onClick={() => this.handleClick()}>调用父组件方法</button>
</div>
);
}
}
```