添加元素后将焦点切换到表

问题描述 投票:0回答:1

我有一个按钮,当按下该按钮时,会将一个新矩阵添加到一个数组,该数组呈现为输入表。我想做的是将焦点添加到数组后,将焦点切换到矩阵的第一个/左上角元素。我知道我可以使用裁判来做到这一点,但我不知道该怎么做。

https://codesandbox.io/s/stoic-hellman-lx1cf

import React, { useState } from "react";
import "./styles.css";

const Matrix = ({matrix}) => {
  return (
    <table>
      {matrix.map((row, _) => (
        <tr>
          {row.map((_, j) => (
            <td>
              <input size = {1}/>
            </td>
          ))}
        </tr>
      ))}
    </table>
  );
};

export default function App() {
  const [matrices, updateMatrices] = useState([]);

  const addMatrix = () => {
    updateMatrices(oldMatrices => {
      oldMatrices.push([[0, 0, 0], [0, 0, 0], [0, 0, 0]]);
      return oldMatrices;
    });
  };

  return (
    <div>
      <button onClick={() => addMatrix()}> Add Matrix </button>
      {matrices.map(matrix => <Matrix matrix = {matrix}/>)}
    </div>
    );
}
javascript html reactjs
1个回答
0
投票

简单地将此行添加到矩阵代码:

<input
autoFocus = {r === 0 && c === 0 ? true: false} 
size={1} />
© www.soinside.com 2019 - 2024. All rights reserved.