【问题标题】:Find out from parent component that child component is mounted in react从父组件中找出子组件挂载在react中
【发布时间】:2020-01-02 10:46:51
【问题描述】:

我有一个反应组件,它有一个子组件。我必须在父组件中知道子组件已安装。该怎么做?

【问题讨论】:

标签: reactjs components


【解决方案1】:

这取决于你使用的 React 版本。

如果你使用的是 React 16.8 或更高版本,你可以在子组件中使用 useEffect 钩子,它可以触发父组件中的函数。

const Parent = props => {
 const OnChildMount = () => {
  console.log('Child Mounted);
 }
 return (
  <Child onMount={OnChildMount}/>
 )
}

const Child = props => {
 useEffect(() => {
  props.onMount();
 }, []);

 return (
  //The child JSX
 );
}

useEffect 钩子中的空括号 [] 确保它仅在安装子组件时运行。

如果您使用的是旧版本的 React,您可以使用子组件中的 ComponentDidMount 生命周期钩子来触发 Parent 中的相同功能。

话虽如此,最终的解决方案实际上取决于您的确切要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 2019-03-11
    • 2021-10-08
    • 2019-04-10
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多