首页 > 解决方案 > 如何在 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 处理程序方法。我怎样才能做到这一点?感谢任何建议。

标签: reactjsjsxuuid

解决方案


  1. 你可以使用闭包

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>
  );
}

  1. 您可以在处理程序中检查该e参数onFocus- 该对象具有对 DOM 元素的引用(类似于 e.target )

推荐阅读