【问题标题】:how to render useState values for only specific div (component)?如何仅为特定的 div(组件)呈现 useState 值?
【发布时间】:2020-10-03 15:45:14
【问题描述】:

我创建了一个包含公式的表格,我希望每个单元格在onBlur 时显示公式的结果,并在onFocus 时显示公式本身。

  • 但问题是,当我单击任何单元格 => 具有值 25 的单元格也会受到影响,尽管我希望单元格 25"=age+3" 仅在精确单击时才会生效(focus on it)
import React, { useState } from "react";
import "./styles.css";
const table = [
  { id: 1, row: ["name", "age", "email",'formula'] },
  { id: 2, row: ["Ali", 23, "alisci@yahoo.com", "=age+3"] },
  { id: 3, row: ["alex", 22, "alexsci@yahoo.com",'22'] }
];
export default function App() {
  const [focused, setFocused] = useState(false);
  const age = table[2].row[1];
  return (
    <table className="App">
      {table.map((item, index) => (
        <tr key={index}>
          {item.row.map((cell, index) => {
            return (
              <td
                onFocus={(e) => setFocused(true)}
                onBlur={(e) => setFocused(false)}
                contentEditable
                key={index}
              >
                {cell[0] === "=" & !focused ? eval(cell.slice(1)) : cell}
              </td>
            );
          })}
        </tr>
      ))}
    </table>
  );
}

on Codesandbox

【问题讨论】:

    标签: reactjs react-hooks rendering


    【解决方案1】:

    您必须跟踪已聚焦的行并进行比较。这是我的尝试。我已将table.map 的索引更改为rowIndex,并在您的条件渲染中检查是否设置了focused,以及它是否等于rowIndex

    OnFocus 函数将 focus 设置为正确的行索引,而 onBlur 将其设置为 null

    https://codesandbox.io/s/xenodochial-carson-2xy4x?file=/src/App.js

    【讨论】:

      【解决方案2】:

      SOLVED

      • 当我检查单元格是否以= 开头时,我将innerText 转换为text
      • 当模糊时,我检查单元格是否以= 开头,然后我将intertext 转换为eval
        onFocus={(e) => cell[0] === "=" && (e.target.innerHTML = cell)}
                      onBlur={(e) =>
                        cell[0] === "=" && (e.target.innerHTML = eval(cell.slice(1)))
                      }
      

      CodeSandBox

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-21
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        • 1970-01-01
        相关资源
        最近更新 更多