[英]Use React componentDidMount in a modal/overlay react component
import { Component } from 'react'
export default class Overlay extends Component {
static propTypes = {
show: React.PropTypes.bool
};
constructor(props, context) {
super(props);
}
render() {
const { show } = this.props;
return (
<div id="overlay">
{show &&
this.props.children
}
</div>
)
}
}
上面是我的疊加組件,我嘗試不使用npm中的任何預制組件,因為我想了解更多有關react的信息。 孩子們被渲染后我該怎么辦?
我在其他組件的某個地方執行<Overlay show={true} />
,現在我想在渲染子代之后做一些事情。 我試過了
componentDidMount(){
console.log('hey');
}
在疊加層組件中,它是首次觸發,但不會在用戶觸發疊加層之后觸發。
您可以使用componentWillReceiveProps生命周期方法-該方法將接收發送到組件的“新”道具,以便您查看是否有任何更改。 可以確保在傳遞給組件的道具發生更改時調用它,但是,在道具沒有更改時也可以調用它,因此有必要手動檢查您感興趣的道具是否已更改。
(如果您在那里沒有執行任何操作,也可以刪除構造函數)
import { Component } from 'react'
export default class Overlay extends Component {
static propTypes = {
show: React.PropTypes.bool
};
componentDidMount() {
console.log("The componentDidMount method is only fired the first time the component is mounted");
componentWillReceiveProps(nextProps) {
// this will run every time the props change - and possibly in addition to this, so we need to check for prop changes
if (this.props.show !== nextProps.show) {
console.log("The show prop changed!);
}
}
render() {
const { show } = this.props;
return (
<div id="overlay">
{show &&
this.props.children
}
</div>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.