我使用react.js,我有一个问题。我有两个组成部分:Child和Parrent。
import React, { Component, Children, cloneElement } from 'react'
import {render} from 'react-dom'
class Child extends Component {
someMethod() {
/* Some code... */
}
componentDidMount() {
/* Some code... */
console.log("Child component did mount!");
}
render() {
return <span>Child</span>
}
}
class Parent extends Component {
componentDidMount() {
/* Some code... */
console.log("Parent component did mount!");
}
render() {
let children = Children.map(this.props.children, (element, idx) => {
return cloneElement(element, { ref: idx });
});
return (
<div>
{children}
</div>
)
}
}
const demo = (
<Parent>
<Child></Child>
</Parent>
);
render(demo,document.querySelector('#demo'));
我需要在子元素(代码中为someMethod
)中使用一个方法,该方法将在parrent元素中运行componentDidMount
后运行。谢谢。
附: React和ReactDom版本为0.14.8
答案 0 :(得分:0)
我找到了解决方案。这不是很好,但它确实有效。
我用setTimeout(..., 0)
在子元素
componentDidMount() {
setTimeout(()=>{
/* Some code which will be run after componentDidMount in parent */
},0);
}