首页 > 解决方案 > 将点击元素的信息作为道具传递给模式 - Reactjs

问题描述

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

下面是我正在尝试的。不幸的是,模态将 targetElement 属性显示为未定义的componentDidMount函数CropperModal

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>

        );
    }
}

标签: reactjsjsxreact-props

解决方案


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

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>

    );


 }
}

推荐阅读