reactjs - 如何在 render() 中的 map() 中创建和分配变量?
问题描述
下面是我正在处理的代码(我已将其修剪以使其可读)。
render() {
return (
<Table.Row>
{ MONTHS.map(month => [ // live forecast, actuals and vs forecasts cells per month
<Table.Cell className="live-forecast-cell">
<Input
ref={el => { this.inputRef[uuid()] = el; }}
onFocus={e => this.handleLiveForecastFocus(supplierName, month, e)}
/>
</Table.Cell>,
]) }
</Table.Row>
);
}
在 map 操作中,我为 ref 生成了一个uuid()值。然后我需要将这个相同的 ref 值传递给 onFocus 处理程序方法。我怎样才能做到这一点?感谢任何建议。
解决方案
- 你可以使用闭包
render() {
return (
<Table.Row>
{ MONTHS.map(month => {
const id = uuid();
return [ // live forecast, actuals and vs forecasts cells per month
<Table.Cell className="live-forecast-cell">
<Input
ref={el => { this.inputRef[id] = el; }}
onFocus={e => {
this.handleLiveForecastFocus(supplierName, month, e);
// this.inputRef[id]
}}
/>
</Table.Cell>,
];}) }
</Table.Row>
);
}
- 您可以在处理程序中检查该
e
参数onFocus
- 该对象具有对 DOM 元素的引用(类似于 e.target )
推荐阅读
- amazon-ec2 - 如何根据自定义标头值将 HTTP 流量分配到属于不同 EKS 集群(都在不同区域)的多个负载均衡器?
- html - 具有最大宽度的 CSS 网格单列
- swift - 向 CollectionView 两列结构添加全宽行
- flutter - flutter_inappwebview 如何将网站列表放入内容拦截器?
- ios - iPadOS 15 UITabBar 标题被截断
- javascript - 如何在多个子域上运行一段代码?
- c# - 如何从 c++ 项目调用 windows 窗体 c# 函数?
- python - 如何在 Ajax 符合数据结构中获取 Django 查询集?
- c# - Azure .NET 5 隔离函数以及如何使用函数绑定更新表存储
- c++ - 为什么 MSVC 编译器/优化器不会删除共享库中重复的函数调用,而是复制整个函数体?