我相信我正在尝试完成一些简单但没有做到的事情。
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
答案 0 :(得分:1)
您不能从这样的父组件中调用子组件的实例函数,而您不能从父组件访问该函数。如果希望两个组件(父级和子级)都可以访问它,则应在它们之间以某种方式共享它,如果层次结构是深层嵌套的,请在更高级别使用context,或在父级中定义并传递通过道具将其交给孩子或使用redux。或者,如果不依赖于组件状态,则将其移出组件。