[英]How to call React/Typescript child component function from parent component?
我正在嘗試在父組件中使用子組件 function “changeName”。 獲取錯誤“App”類型上不存在屬性“superheroElement”。 解決這個問題的最佳方法是什么? 子組件和父組件如下
import React,{Component} from 'react';
class Superhero extends React.Component {
state = {
name: "Batman"
};
changeName = () => {
this.setState({
name: "Bruce Wayne"
});
};
render(){
return <div>{this.state.name}</div>;
}
}
export default Superhero;
import React, { Component, RefObject } from 'react';
import Superhero from './child'
class App extends React.Component<any , any> {
constructor(props:any) {
super(props);
this.superheroElement = React.createRef();
}
handleClick = () => {
this.superheroElement.current.changeName();
};
render() {return
<div><Superhero ref={this.superheroElement}/>
<button onClick={this.handleClick}>real name</button></div>
}
}
export default App;
首先,我不認為這是 React 應用程序的最佳實踐,因為這與 React 的單向數據流相反。 所以,這個參考想法應該只是最后的手段。
對於您的問題,防止錯誤的最簡單方法是將 superheroElement 設置為 any。
import React from 'react';
import Superhero from './child'
class App extends React.Component<any, any> {
superheroElement: any;
constructor(props: any) {
super(props);
this.superheroElement = React.createRef();
}
handleClick = () => {
this.superheroElement.current.changeName();
};
render() {return
<div><Superhero ref={this.superheroElement}/>
<button onClick={this.handleClick}>real name</button></div>
}
}
export default App;
這樣,錯誤就會消失。 但是,如果您想保留 typescript 功能,您可以為 RefObject 指定類型。
import React, { RefObject } from 'react';
import Superhero from './child';
class App extends React.Component<any, any> {
superheroElement: RefObject<Superhero>;
constructor (props: any) {
super(props);
this.superheroElement = React.createRef();
}
handleClick = () => {
if (this.superheroElement.current)
this.superheroElement.current.changeName();
};
render () {
return (
<div>
<Superhero ref={this.superheroElement} />
<button onClick={this.handleClick}>real name</button>
</div>
);
}
}
export default App;
注意:您可以將孩子的類型賦予 createRef。
this.superheroElement = React.createRef<Superhero>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.