如何仅为特定的div(组件)呈现useState值?

时间:2020-10-03 15:45:14

标签: reactjs react-hooks rendering

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

  • 但是问题是,当我单击任何单元格=>时,尽管我希望将单元格2525设为"=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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

SOLVED

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

CodeSandBox