加载弹出组件

时间:2019-07-18 01:38:00

标签: reactjs

我正在尝试在弹出窗口中显示详细信息组件。我的App.js组件包含一个List组件和Item组件列表。单击“项目组件”时,我要显示“详细信息”弹出窗口。 togglePopup()函数从父级列表组件传递到子项,然后传递到详细信息。现在,弹出窗口没有显示。下面是我的代码: App.js

class App extends Component  {
state={ showPopup: false,
        selectedItem:'',
        Items:[]};
togglePopup=()=> {  
    this.setState({  

   showPopup: !this.state.showPopup  
    });  
}  
 onItemseSelect=(item)=>{
    this.setState({selectedItem:item});
  };

render(){
    const Items=['aa','bb','cc'];
    return(

    <List 
    Items={this.state.Items}
    onItemSelect={this.onItemSelect}
    onClick={this.togglePopup}
    />


{this.state.showPopup ?  
    <Detail  
      item={this.state.selectedItem}
      closePopup={this.togglePopup.bind(this)}  
    />  
    : null  
    }  

);
}
}

List.js

import React  from 'react';
    import Item from './Item';

    const List=({Items,onItemSelect,onClick})=>{
        const renderedList= Items.map(item=>{
        return (
        <Item key={item.ID} item={item} onItemSelect={onItemSelect}   onClick={onClick} />
        );
    })
    return <div>

    {renderedList}</div>
    }

    export default List;

Item.js

import React from 'react';
    const Item=({item, onItemSelect,onClick})=>{
        return <div  onClick={()=>onItemSelect(item)} >
    <div class="content">
    <div class="header">
     {/*display contents*/}
     <button onClick={onClick}>View More</button>
    </div>
    </div>
    };
    export default Item;

Detail.js

import React from 'react';

    const Detail=({item,closePopup})=>{
        if (!item){
        return <div>loading</div>
        }

       return (
       <div>
         <p>
         {/*contents here*/}
         </p>

        <button onClick={()=>closePopup}>close me</button>
    </div>);
     };
    export default Detail;

1 个答案:

答案 0 :(得分:0)

您尚未将状态设置为显示弹出窗口,请执行此操作

onItemseSelect=(item)=>{
    this.setState({selectedItem:item, showPopup: true}); //make showPopup to true so that popup get displayed
};

注意:在使用箭头功能时,无需在此处绑定this

closePopup={this.togglePopup.bind(this)}

您可以将其更改为

closePopup={this.togglePopup}

另一件事是,不要这样做,

<div  onClick={()=>onItemSelect(item) togglePopup={togglePopup}} > //This is wrong way to call two functions
<div  onClick={()=> {onItemSelect(item); togglePopup;}} > //This is right way to call two functions

如果您在每次点击项目时调用togglePopup,那么每次selectedItem:''都会将项目设置为blank,您将无法在页面上看到任何内容


旁注Detail是组件而不是popup。在App获得this.state.showPopup值之后,该组件将在true组件上显示。要将其显示为popup,您必须使用Modal