Javascript React条件呈现:(a)等待装入子级

Javascript React条件呈现:(a)等待装入子级,javascript,reactjs,asynchronous,async-await,Javascript,Reactjs,Asynchronous,Async Await,我有一个React类组件,默认情况下呈现null,调用activate()函数后还有一些子类。大致如下: class MyComponent extends React.Component { ... activate() { this.setState({showComponent: true}) } ... render() { if (this.state.showComponent) {

我有一个React类组件,默认情况下呈现
null
,调用
activate()
函数后还有一些子类。大致如下:

class MyComponent extends React.Component {

    ...

    activate() {

        this.setState({showComponent: true})

    }

    ...

    render() {
        if (this.state.showComponent) {
            return <Child />
        } else {
            return null
        }
    
    }
}

类MyComponent扩展了React.Component{ ... 激活(){ this.setState({showComponent:true}) } ... render(){ if(this.state.showComponent){ 返回 }否则{ 返回空 } } } 我有一个外部JavaScript脚本,其中我与
MyComponent
(调用激活函数)交互

简而言之,我的问题是,在这个外部JS脚本中调用activate()并尝试访问
组件中的HTMLElements之后(使用
document.getElementById
),当
组件稍后异步呈现时,我会得到空指针

是否有办法使
MyComponent
中的
activate()

我已经尝试利用setState的异步特性,并尝试使用
等待此。setState({showComponent:true})
执行
async activate()

简而言之,有没有一种方法可以在执行setState更新后等待子对象被渲染。我想这是一个有点特殊的情况,因为它涉及到条件渲染,而
MyComponent
最初不渲染任何内容


对任何想法都感到高兴!:)

如何在
Child
组件的
componentDidMount
内的窗口对象上发出一个自定义事件,并在外部javascript中侦听该事件,并访问事件处理程序中的HTML元素。

我们可以向子组件传递一个函数,我们可以在子组件的componentDidMount钩子中调用该函数,所以当孩子被挂载时,它会触发这个函数。。。但请记住,不要在传递的函数中更新父组件的任何状态变量,否则它将卡在循环中(因为随着状态变量的更改,它将重新呈现所有子组件,并且最终也将调用组件装载…)


安装 }


}

我建议改为使用
useffect
。您好,谢谢您的回答。像这样的东西我已经实现了。但是我不知道这个回调函数的内容是什么。我怎么能等到所有的孩子都用这个来呈现呢?非常感谢,这个效果非常好!只是想知道是否有一个解决方案使用本机React来实现这一点,所以所有的逻辑都保留在React组件中。例如,我的直觉告诉我必须有一种方法来利用setState中的回调参数。他还尝试了与@sourav choudhary的建议类似的方法,但没有找到一种内在地延迟激活功能返回的方法。还考虑了返回一个promise.AFAIK,
MyComponent
的状态更改为
{showComponent:true}
时,
子组件将不会立即装入。我敢肯定会有延误,你可能会遇到同样的问题。我认为确保元素存在的最佳方法是在
子组件中使用
componentDidMount
    class MyComponent extends React.Component {

        ...

        activate() {

       this.setState({showComponent: true})

    }

        callback = ()=>{
       // function to be passed in child component 
      // don't update any state variable here .. 
        }

      ...

     render() {
      if (this.state.showComponent) {
        return <Child callback={this.callback} />
     } else {
         return null
     }

  }
}
  class child extends React.Component {
    constructor (props){
    super(props)
 }

   componentDidMount(){
     this.props.callback() // this will be called when this child will be