我有一个包含此Modal组件的列表 . 如果用户单击列表中的某一行,则该行中的道具将向下传递到 Modal Component
.
当道具传递给Modal时,我想调用 componentWillReceiveProps
来设置作为Modal状态的一部分传递的道具 . 我这样做是因为像 title
, status
和 cost
这样的道具最终将成为通过Modal状态更新的受控输入 .
我唯一的问题是 componentWillReceiveProps
只被调用一次并且道具不会传递到Modal的状态 . 有没有办法将这些道具作为状态传递给子组件?
我正在使用React-Bootstrap的模态
父组件:
<AdditionalPaymentsModal
status={'New'}
id= {null}
title={'testong'}
cost={''} />
子组件:
class AdditionalPaymentsModal extends Component {
constructor(props){
super(props);
this.state = {
showModal: this.props.showModal,
};
this.close = this.close.bind(this);
this.open = this.open.bind(this);
}
close() {
this.setState({ showModal: false });
}
open() {
this.setState({ showModal: true });
}
componentWillReceiveProps(nextProps){
console.log("SETTING THE STATE", this.state);
this.setState({
id: nextProps.id,
title:nextProps.title,
status: nextProps.status,
cost:nextProps.date
})
}
render(){
const {id, title, status, cost} = this.props;
return (
<div>
<Button
onClick={this.open}>
Open
</Button>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>New Edit Cost</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.state.title}
{this.state.id}
{this.state.cost}
{this.state.status}
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Cancel</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
1 回答
它没有't look like you'重新修改传入的
props
;如果你're just looking to display them then they don' t需要在state
.你已经在
render
函数中初始化了道具:const {id, title, status, cost} = this.props;
所有你需要做的就是引用这些 - 你的构造函数不需要将它们放在_3038779中:
render () { ... <Modal.Body> {title} {id} {cost} {status} </Modal.Body> ... }