如何在 render() 中的 map() 中创建和分配变量?
How to create and assign a variable within a map() which is in render()?
下面是我正在处理的代码(我已将其缩减以使其可读)。
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>
);
}
- 您可以在
onFocus
处理程序中检查 e
参数 - 该对象引用了 DOM 元素(类似于 e.target )
render() {
return (
<Table.Row>
{ MONTHS.map(month => { // live forecast, actuals and vs forecasts cells per month
const uuidValue = uuid()
return (
<Table.Cell className="live-forecast-cell" key={'ADD_A_UNIQUE_KEY_HERE'}>
<Input
ref={el => { this.inputRef[uuidValue] = el; }}
onFocus={e => this.handleLiveForecastFocus(supplierName, month, e, uuidValue)}
/>
</Table.Cell>
)
}) }
</Table.Row>
);
}
下面是我正在处理的代码(我已将其缩减以使其可读)。
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>
);
}
- 您可以在
onFocus
处理程序中检查e
参数 - 该对象引用了 DOM 元素(类似于 e.target )
render() {
return (
<Table.Row>
{ MONTHS.map(month => { // live forecast, actuals and vs forecasts cells per month
const uuidValue = uuid()
return (
<Table.Cell className="live-forecast-cell" key={'ADD_A_UNIQUE_KEY_HERE'}>
<Input
ref={el => { this.inputRef[uuidValue] = el; }}
onFocus={e => this.handleLiveForecastFocus(supplierName, month, e, uuidValue)}
/>
</Table.Cell>
)
}) }
</Table.Row>
);
}