solution
Q:React
中,父组件如何调用子组件的方法?
task
利用props
传值解决,不使用ref
我们知道父组件可以靠子组件调用函数传参作为返回值,那么同样道理,函数也能作为参数从子组件传回父组件
,这样,在父组件中就能调用子组件的方法了
action
父组件Expenses
中定义函数handleClick
,将其作为参数传入子组件CommonText
,子组件接收父组件传入的handleClick
并在自己的点击事件中执行,传入事先定义好的方法test
作为形参
执行程序
在父组件的handleClick
方法中接收子组件传入的参数,就能执行我们子组件的方法了
父组件Expenses
代码
import CommonText from "../components/commonText";
import { PureComponent} from "react";
class Expenses extends PureComponent {
constructor(props) {
super(props);
}
handleClick = (func) => {
func()
}
render() {
return (
<main style={{padding: "1rem 0"}}>
<CommonText handleFunc={this.handleClick}/>
<h2>
泥嚎,我是小陈的第二个页面
</h2>
</main>
)
}
}
export default Expenses;
子组件CommonText
代码
import {PureComponent} from "react";
class CommonText extends PureComponent {
constructor(props) {
super(props);
}
test = () => {
console.log(1)
}
handleTest = () => {
const {handleFunc} = this.props;
handleFunc(this.test)
}
render() {
return (
<div onClick={this.handleTest}>
<h2>我是子组件commonText</h2>
</div>
);
}
}
export default CommonText;
result
以前学习父子组件通信时,没有考虑到这一层,前不久遇到了这个问题,刚好今天来付诸实践后得到答案,也能加深自己对父子组件通信的理解