反应:调用“ componentDidMount”时this.reference.current为null

时间:2019-01-31 19:17:41

标签: javascript reactjs reference

我正在尝试访问this.myref.current,但是在调用componentDidMount时无法执行。当所有引用都链接在一起时,我还能调用另一个函数吗?

请注意,问题不仅在于我无法访问.current,而且更具体地说,是我在componentDidMount期间无法访问它。我以后可以在其他事件上访问它。

export default class Parentextends Component {
    constructor(props) {
        super(props);
        this.myref = React.createRef();
    }

    componentDidMount() {
        this.myref.current.childmethodname(); // this.myref.current is null
    }

    MyFn = () => {
        this.myref.current.childmethodname(); // This works
    }

    render() {
        return (<Child ref={this.myref} />);
    }
}

1 个答案:

答案 0 :(得分:0)

正如Felix在他的评论中所述,在我看来,Child组件是无状态(功能性)组件,正如您在this CodeSandbox中看到的那样,在使用有状态(类)组件时一切正常。 / p>