Javascript 不从另一个组件调用函数?
我相信我正在努力完成一些简单的事情,但没有做到 React没有像我希望的那样从另一个组件的ChildComponent调用“alertFunc()” 以下是儿童用品:Javascript 不从另一个组件调用函数?,javascript,reactjs,components,Javascript,Reactjs,Components,我相信我正在努力完成一些简单的事情,但没有做到 React没有像我希望的那样从另一个组件的ChildComponent调用“alertFunc()” 以下是儿童用品: class ChildComp extends React.Component { constructor(props) { super(props); this.state = { }; this.input = React.createRef(); }
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} />
);
}
}
您不能像这样从父组件调用子组件的实例函数,您无权从父组件访问该函数。如果您希望两个组件都可以访问它(父组件和子组件),您应该以某种方式在它们之间共享它,如果层次结构嵌套得很深,则在更高的级别上使用,或者在父组件中定义它并通过道具传递给子组件,或者使用redux。或者,如果不依赖于组件状态,则将其移出组件。请花时间编写适当的MCVE,同时显示父组件。有根据的猜测:如果该函数是在子组件中定义的,那么它如何在父组件中调用/可用?请提供父组件的代码Fair point将花时间提供有关此问题的更多代码
render(props){
return(
<button onClick={props.alertFunc()}>Next</button>
);
}
props.alertFunc is not a function