我在将状态从父组件转发到子组件时遇到问题,这两个组件是类组件。将状态从父组件转发到子组件时,我想在子组件中使用 state showModal 变量作为显示状态变量:
this.state = {
show: this.props.show
}
此变量用于激活模态。当我将它用作 this.props.show 时,状态已被转发到子组件并更新,但是当我在子组件中使用 this.state 中的道具时,它尚未更新。有谁知道问题出在哪里?
第一 - 父组件:
import React, { Component } from 'react';
import Modal from './UI/Modal';
class EnteredBooks extends Component {
constructor(props) {
super(props)
this.state = {
enteredBook: this.props.enteredBook,
showModal: false
}
}
detailsHandler = () => {
this.setState({
showModal: true
})
}
render() {
let show = this.state.showModal;
return (
<div>
<div className="product">
<img src="{this.props.enteredWatch.bookUrl}" />
<p>{this.props.enteredWatch.bookType}</p>
<p>euro{this.props.enteredWatch.bookPrice}</p>
<button
className="details-button"
onClick={this.detailsHandler}
>
Details
</button>
<Modal show={this.state.showModal} watch={this.state.enteredWatch} />
<button className="buy-button">Buy</button>
</div>
</div>
);
}
}
export default EnteredWatches;
第二 - 子组件:
import React, {Component} from 'react';
import classes from './Modal.css';
class Modal extends React.Component {
constructor(props) {
super(props)
this.state = {
book: this.props.book,
show: this.props.show
}
}
return(
<div>
<div className="Modal"
style={{
transform: this.state.show ? 'translateY(0)' : 'translateY(-100vh)',
opacity: this.state.show ? '1':'0'
}}>
<img src={this.state.book.bookUrl} />
<p>{this.state.book.bookType}</p>
<p>{this.state.book.watchUrl}</p>
<button className="details-button">Details</button>
<button className="buy-button">Buy</b
</div>
</div>
);
}
}
export default Modal;
constructor
只运行一次。适用于计算初始状态。但这种情况就是getDerivedStateFromProps
钩子的用途。它允许在每次更新组件时从 props 计算状态,包括初始化:
static getDerivedStateFromProps(props) {
return {
book: props.book,
show: props.show
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句