我有一个如下所示的基于类的父组件
A
import React from "react";
import ReactDOM from "react-dom";
import FunChild from "./FunChild";
class App extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
this.parentmethodFun = this.parentmethodFun.bind(this);
}
parentmethodFun() {
this.childRef.current.childmethod();
}
render() {
return (
<div>
<FunChild />
<button type="button" onClick={this.parentmethodFun}>
function
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
文件
funChild.js
如果那个孩子是一个类组件,我可以很容易地使用 import React from "react";
function FunChild(props) {
childmethod() {
console.log("child method is called");
}
return (<div>This is child ...!</div>);
}
export default FunChild;
来访问孩子的方法。
但是,它是一个功能组件,它带来了很多问题。任何人都可以帮我解决这个问题。
参考项目链接https://codesandbox.io/s/react-playground-forked-74xzn?file=/index.js
答案 0 :(得分:0)
你应该避免这种关系,因为它不是 react 的工作方式。在 React 中,您应该从上到下传递所有内容。但是如果你真的想实现这样的事情,你可以使用引用转发和imperative handler hook。例如:
import { Component, forwardRef, createRef, useImperativeHandle } from "react";
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
childMethod() {
console.log("child method is called");
}
}));
return <div>This is child ...!</div>;
});
class App extends Component {
constructor(props) {
super(props);
this.childRef = createRef();
this.parentmethodFun = this.parentmethodFun.bind(this);
}
parentmethodFun() {
this.childRef.childMethod();
}
render() {
return (
<div>
<Child ref={(ref) => (this.childRef = ref)} />
<button type="button" onClick={this.parentmethodFun}>
function
</button>
</div>
);
}
}
就我个人而言,我认为您应该重新考虑您的应用程序结构,因为很可能有比这个技巧更好的解决方案。