javascript - 反应模态自定义组件未显示正确数据
问题描述
我已经使用反应钩子构建了这个模态组件。但是,模式弹出时显示的数据不正确(它始终显示数组中最后一个元素的名称属性)。
//Modal.js
import ReactDOM from 'react-dom';
const Modal = ({ isShowing, hide, home_team }) => {return isShowing ? ReactDOM.createPortal(
<React.Fragment>
<div className="modal-overlay"/>
<div className="modal-wrapper">
<div className="modal">
<div className="modal-header">
<a>Home team: {home_team}</a>
<button type="button" className="modal-close-button" onClick={hide}>
</button>
</div>
</div>
</div>
</React.Fragment>, document.body
) : null;}
export default Modal;
// 主要组件
const League = ({ league, matches }) =>{
const {isShowing, toggle} = useModal();
return (
<Fragment>
<h2>{league}</h2>
{
matches.map((
{
match_id,
country_id,
home_team
}
) =>
{
return (
<div>
<p>{match_id}</p>
<button className="button-default" onClick={toggle}>Show Modal</button>
<a>{home_team}</a>
<Modal
isShowing={isShowing}
hide={toggle}
home_team={home_team}
/>
<p>{home_team}</p>
</div>
)
})
}
</Fragment>
)};
这是匹配数据集的样子:
[{
match_id: "269568",
country_id:"22",
home_team: "Real Kings"
},
{
match_id: "269569",
country_id:"22",
home_team: "Steenberg United"
},
{
match_id: "269570",
country_id:"22",
home_team: "JDR Stars "
},
{
match_id: "269571",
country_id:"22",
home_team: "Pretoria U"
},
]
我不确定发生了什么,因为数据似乎可以正常传递。
<p>{home_team}</p>
在主组件中每次都显示预期的属性,但是模态总是显示home_team
数组中的最后一项(例如比勒陀利亚 U)
解决方案
您需要在 map 函数中调用 useModal 。否则,您将在切换所有模态时打开,最后一个与其他模态重叠
const HomeTeam = ({ match_id, country_id, home_team }) => {
const {isShowing, toggle} = useModal();
return (
<div>
<p>{match_id}</p>
<button className="button-default" onClick={toggle}>Show Modal</button>
<a>{home_team}</a>
<Modal
isShowing={isShowing}
hide={toggle}
home_team={home_team}
/>
<p>{home_team}</p>
</div>
)
}
const League = ({ league, matches }) => (
<Fragment>
<h2>{league}</h2>
{ matches.map((match) => <Hometeam {...match} /> }
</Fragment>
);
推荐阅读
- php - 如何仅按日期搜索数据
- node.js - 如何使用猫鼬创建多站点 url 以将特定信息存储到特定站点
- html - 如何正确地将水平滚动菜单放入 flexbox 布局中
- r - R Markdown 关键字未出现在文档中
- windows - Windows 在 Perl 命令中将除法运算符 '/' 作为反斜杠 '\'
- pyspark - 如何使用 pyspark 检查文件/文件夹是否存在而不会出现异常
- c# - 检查用户是否存在并返回用户 + 角色 EF6
- apache-nifi - Kafka 处理器不保留流文件的属性状态
- angular - 如何实现多选框
- node.js - 如何使用 TypeORM 查找选项获取关系表列?