【问题标题】:React not calling function from another component?反应不从另一个组件调用函数?
【发布时间】:2020-07-13 10:54:03
【问题描述】:

我相信我正在尝试完成一些简单的事情,但没有做到。

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

【问题讨论】:

  • 请花时间编写一个适当的 MCVE,同时显示父组件。有根据的猜测:如果函数是在 CHILD 组件中定义的,那么它如何在 PARENT 中被调用/可用?
  • 请提供父组件的代码
  • 公平点,将花时间提供有关此问题的更多代码

标签: javascript reactjs components


【解决方案1】:

您不能像这样从父组件调用子组件的实例函数,您无权从父组件访问该函数。如果您希望两个组件都可以访问它(父组件和子组件),您应该在它们之间以某种方式共享它,如果层次结构嵌套很深,则在更高级别使用context,或者在父组件中定义它并将其传递给孩子通过道具或使用redux。或者,如果不依赖于组件状态,则将其移出组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多