简体   繁体   English

反应不从另一个组件调用 function?

[英]React not calling function from another component?

I believe I am trying to accomplish something simple but failing to do so.我相信我正在尝试完成一些简单但未能做到的事情。

React is not calling the 'alertFunc()' from the ChildComponent from another component like I hoped it would. React 并没有像我希望的那样从另一个组件的 ChildComponent 调用“alertFunc()”。

Here is the ChildComp:这是 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} />
        );
    }
}

Then I'm trying to call it from a parent compolike:然后我试图从父类compolike中调用它:

render(props){

    return(
        <button onClick={props.alertFunc()}>Next</button>
    );

}

And the error I get is:我得到的错误是:

props.alertFunc is not a function

You can't call an instance function of a child component from a parent component like that, you don't have access to that function from the parent.您不能像这样从父组件调用子组件的实例 function,您无权从父组件访问该 function。 If you wish both components to have access to it (parent and child) you should share it somehow between them, using context at a more upper-level if the hierarchy is deeply nested, or define it in the parent and pass it to the child via props or use redux.如果您希望两个组件都可以访问它(父组件和子组件),您应该在它们之间以某种方式共享它,如果层次结构嵌套很深,则在更高级别使用上下文,或者在父组件中定义它并将其传递给子组件通过道具或使用 redux。 Or if doesn't depend on component state move it out of the component.或者如果不依赖于组件 state 将其移出组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM