[英]React not calling function from another component?
我相信我正在嘗試完成一些簡單但未能做到的事情。
React 並沒有像我希望的那樣從另一個組件的 ChildComponent 調用“alertFunc()”。
這是 ChildComp:
class ChildComp extends React.Component {
constructor(props) {
super(props);
this.state = { };
this.input = React.createRef();
}
alertFunc = () => {
alert('This function is called from the Child Component');
};
handleChange = () => {
this.alertFunc();
};
render() {
return (
<ChildComp onChange={this.handleChange} />
);
}
}
然后我試圖從父類compolike中調用它:
render(props){
return(
<button onClick={props.alertFunc()}>Next</button>
);
}
我得到的錯誤是:
props.alertFunc is not a function
您不能像這樣從父組件調用子組件的實例 function,您無權從父組件訪問該 function。 如果您希望兩個組件都可以訪問它(父組件和子組件),您應該在它們之間以某種方式共享它,如果層次結構嵌套很深,則在更高級別使用上下文,或者在父組件中定義它並將其傳遞給子組件通過道具或使用 redux。 或者如果不依賴於組件 state 將其移出組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.