首页 > 解决方案 > 如何聚焦表格行?

问题描述

当用户按下 cmd+rightarrow 时,我尝试将焦点设置在表中的最后一行。以这种方式,用户应该能够在不使用鼠标的情况下选择 8 个行元素中的任何一个。键绑定工作完美(并添加了事件侦听器),但引用有问题。

const selRef = useRef<any>();

const onKeyDown = (e) => {
    if ((e.ctrlKey || e.metaKey) && ['ArrowRight'].includes(e.key)) {
        selRef.current.focus();
    }

return (
                    <tbody>
                        {value.map((trip, index) => (
                            <div>
                                <tr
                                    onClick={() =>
                                        props.onSelect(trip, 'copy')
                                    }
                                    key={`history-row-${index}`}
                                    className={styles.focused}
                                    ref={selRef}
                                >
                                    <td id="sr-td-shortcut">{index + 1}</td>
                                    <td id="sr-td-pick">
                                        {genFormattedAddress(trip.start)}
                                    </td>
                                    <td id="sr-td-drop">
                                        {genFormattedAddress(trip.end)}
                                    </td>
                                </tr>
                            </div>
                        ))}
                    </tbody>
    )

标签: reactjsreact-hooks

解决方案


tr默认情况下元素不能接受焦点。tabindex={0}要启用焦点行为,请添加<tr>


推荐阅读