【发布时间】:2020-12-01 15:57:35
【问题描述】:
我想访问模态框上单击项目的 id 等属性。如何在点击时将目标属性作为道具传递给模态。
以下是我正在尝试的。不幸的是,模态在CropperModal 的componentDidMount 函数中将targetElement 属性显示为未定义
export default class DynamicArticleList extends React.Component {
constructor(){
super();
this.state={
targetElement: '',
}
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
showModal(e){
this.setState({
targetElement: e.target.getAttribute("id")
})
}
hideModal(e){
this.setState({
showing: false,
showSource: '#',
})
}
render() {
return (
<div className="wrapper container-fluid DynamicArticleList">
<div className="width-control">
<img src="../img/journey.jpg" onDoubleClick={this.showModal} id="Img0"/>
<CropperModal targetElement={this.state.targetElement}/>
</div>
</div>
);
}
}
【问题讨论】:
-
您的
img元素没有分配 ID 属性。 -
感谢您的突出显示,我的代码非常复杂,所以我在这里简化了它,忘记添加 id 但在我的代码中 id 在那里。顺便说一句,我编辑了问题。
-
您正在等待 targetElement 出现在 ComponentDidMount 中。如果您有与您附加的代码相同的代码,那么您从一开始就渲染 CropperModal,然后您将 targetElement 添加到您的状态。您需要在 CropperModal 中使用 ComponentDidUpdate 或 getDerivedStateFromProps )
-
这会如何改变场景? @jamomani
-
我试图在这里重现它:codesandbox.io/s/… -- 似乎工作正常。
标签: reactjs jsx react-props