我试图在弹出窗口中显示一个详细组件。我的App.js组件包含一个包含项目组件列表的列表组件。单击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;发布于 2019-07-18 01:50:59
您尚未将状态设置为显示弹出窗口,请执行以下操作
onItemseSelect=(item)=>{
this.setState({selectedItem:item, showPopup: true}); //make showPopup to true so that popup get displayed
};注意:在使用箭头函数时,不需要在这里绑定,
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。
https://stackoverflow.com/questions/57085942
复制相似问题