【发布时间】:2021-05-16 10:11:35
【问题描述】:
我有一个 15 x 15 的 html 表格形式的矩阵,每个单元格中都有一个输入框。我希望它让用户只能:
- 输入英文字母
- 删除一个字符(退格)
- 使用空格键
- 以后,我希望他们能够使用箭头键来导航矩阵
到目前为止,下面的代码允许我检查它是否是英文字母,但我不能使用退格键、空格键,也不能更新单元格。
以下是我的矩阵代码以及我如何更新值:
const matrix = [];
for(let i = 0; i < 15; i++){
const row = [];
for(let j = 0; j< 15; j++){
row.push("")
}
matrix.push(row)
}
const [board,setBoard] = useState(matrix);
const handleBoardChange = (event,row,col) => {
if((event.target.value.charCodeAt(0) >= 65 &&
event.target.value.charCodeAt(0) <= 90) ||
event.target.value.charCodeAt(0) === 32 ||
(event.target.value.charCodeAt(0) >= 97 &&
event.target.value.charCodeAt(0) <= 122))
{
let copy = [...board]
copy[row][col] = event.target.value
setBoard(copy)}
}
return (
<div className="analysis-section">
<Board
board={board}
handleBoardChange ={handleBoardChange}
/>
</div>
);
}
这是矩阵本身:
const Board = ({board,handleBoardChange}) => {
let rows = [];
for (var i = 0; i < 15; i++){
let rowID = `row${i}`
let cell = []
for (var idx = 0; idx < 15; idx++){
let cellID = `cell${i}-${idx}`
let row = `${i}`
let col = `${idx}`
cell.push(
<td key={cellID} id={cellID}>
<div>
<input
type="text"
maxLength="1"
value = {board[parseInt(row)][parseInt(col)]}
onChange = {(e) => {
handleBoardChange(e,parseInt(row),parseInt(col))}
}
>
</input>
</div>
</td>)
}
rows.push(<tr key={i} id={rowID}>{cell}</tr>)
}
return (
<div className="board">
<table>
{rows}
</table>
</div>
);
}
export default Board
感谢您的帮助,谢谢!
【问题讨论】:
标签: javascript html reactjs