我创建了一个包含公式的表格,我希望每个单元格在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>
);
}
答案 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)))
}