[英]Typescript + React call parent method from child component
我正在嘗試從子組件中調用父方法,但是它不起作用,並且未觸發父元素中的方法。 在此示例中,我只有兩個組件,其中ChildHello
在Hello
組件中調用方法。
Hello.tsx
import * as React from "react";
interface Props {
itemClicked: () => void;
}
export class Hello extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
itemClicked = val => {
console.log(val);
};
render() {
const { name } = this.props;
return <h1 itemClicked={this.itemClicked}>{this.props.children}</h1>;
}
}
const styles = {
height: "400px"
};
export class ChildHello extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
render() {
return (
<div onClick={this.props.itemClicked} style={styles}>
<Hello>Hello Child</Hello>
</div>
);
}
}
您需要了解使用click事件的childHello中的父子關系。
<div onClick={this.props.itemClicked} style={styles}>
<Hello>Hello Child</Hello>
</div>
childhello由index.jsx頁面調用
<div style={styles}>
<ChildHello name="CodeSandbox" />
</div>
在這里,您沒有傳遞任何點擊事件。 另外,hello組件位於子組件內部,這是錯誤的。
所有父組件都應包含click方法,並且該方法應作為props傳遞。
像這樣
家長:
<div style={styles}>
<Hello name="CodeSandbox" />
</div>
你好組件
render() {
const { name } = this.props;
return <ChildHello itemClicked={this.itemClicked} />;
}
ChildHello
render() {
return (
<div onClick={this.props.itemClicked} style={styles}>
Hello
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.