【问题标题】:Pass clicked element's information to a modal as props - Reactjs将点击元素的信息作为道具传递给模式 - Reactjs
【发布时间】:2020-12-01 15:57:35
【问题描述】:

我想访问模态框上单击项目的 id 等属性。如何在点击时将目标属性作为道具传递给模态。

以下是我正在尝试的。不幸的是,模态在CropperModalcomponentDidMount 函数中将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


【解决方案1】:

这就是我的做法。我基本上避免模态组件渲染,直到点击事件被处理

export default class DynamicArticleList extends React.Component {

constructor(){
    super();
     this.state={
         showing: false,
         targetElement: '',
        
         
    }
 
    this.showModal = this.showModal.bind(this);
    this.hideModal = this.hideModal.bind(this);

}

showModal(e){
    
    this.setState({
        showing: true,
        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"/>
               {this.state.showing ? <CropperModal targetElement={this.state.targetElement}/> : null}                  
            
            </div>
        </div>

    );


 }
}

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2019-06-28
    • 2020-11-19
    相关资源
    最近更新 更多