我知道如何从父类调用子方法。但现在,当我想从另一个 child 调用子方法时,我遇到了问题。
如何从 UserAuthenticationUI 类调用 UserAuthenticationRequests 类中声明的 testMethod() ? 可以毫无问题地从 App 类调用 testMethod()。
(我不需要从 App 类中调用它,只是举例)
父类
import React from 'react';
import UserAuthenticationUI from './UserAuthentication/UserAuthenticationUI';
import UserAuthenticationRequests from './UserAuthentication/UserAuthenticationRequests';
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.userAuthenticationRequests = React.createRef();
}
componentDidMount(){
this.userAuthenticationRequests.current.testMethod(); //there i can call method without problems
}
render(){
return(
<div>
<UserAuthenticationUI ref={this.userAuthenticationUI} />
<UserAuthenticationRequests ref={this.userAuthenticationRequests} />
<div>
)}
}
export default App;
<强>1。我想调用2.child方法的child
import React from "react";
import App from '../App';
import UserAuthenticationRequests from './UserAuthenticationRequests';
class UserAuthenticationUI extends React.Component {
constructor(props){
super(props);
this.app = React.createRef();
this.userAuthenticationRequests = React.createRef();
}
componentDidMount() {
this.userAuthenticationRequests.current.testMethod(); //there i can not call
}
render(){
return(
<div>
<App/>
<UserAuthenticationRequests ref={this.userAuthenticationRequests} />
</div>
)}
}
export default UserAuthenticationUI;
出现此错误
TypeError: Cannot read property 'testMethod' of null
<强>3。 2.从父级和子级调用的类
class UserAuthenticationRequests extends React.Component {
testMethod(){
console.log("test method")
}
render(){
return(<div></div>)
}
}
export default UserAuthenticationRequests;
最佳答案
当多个兄弟组件想要使用相同的方法或属性时,建议提升该状态或方法。此外,您必须在尽可能少的情况下使用 refs。在你的情况下,你会这样写
应用程序
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.userAuthenticationRequests = React.createRef();
}
componentDidMount(){
this.testMethod();
}
testMethod(){
console.log("test method")
}
render(){
return(
<div>
<UserAuthenticationUI testMethod={this.testMethod} ref={this.userAuthenticationUI} />
<UserAuthenticationRequests testMethod={this.testMethod} ref={this.userAuthenticationRequests} />
<div>
)}
}
export default App;
用户身份验证请求
class UserAuthenticationRequests extends React.Component {
render(){
return(<div></div>)
}
}
export default UserAuthenticationRequests;
用户身份验证UI
class UserAuthenticationUI extends React.Component {
constructor(props){
super(props);
this.app = React.createRef();
this.userAuthenticationRequests = React.createRef();
}
componentDidMount() {
this.props.testMethod();
}
render(){
return(
<div>
<App/>
<UserAuthenticationRequests ref={this.userAuthenticationRequests} />
</div>
)}
}
export default UserAuthenticationUI;
关于javascript - 从子到子的访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51436680/