gpt4 book ai didi

javascript - 带 React 的流动 tabindex

转载 作者:行者123 更新时间:2023-12-03 13:32:06 25 4
gpt4 key购买 nike

在 React 中制作“移动 tabindex”最简单的方法是什么?它基本上是在子元素之间切换焦点和 tabindex=0/-1 。只有一个元素的 tabindex0,而其他元素的 tabindex-1。箭头键在子元素之间切换 tabindex,并将其聚焦。

现在,我对所需类型进行了简单的子级映射,并设置 index 属性并获取 ref ,以供稍后使用。它看起来很强大,但可能有更简单的解决方案吗?

我当前的解决方案(伪javascript,仅用于说明想法):

ElementWithFocusManagement.js

function recursivelyMapElementsOfType(children, isRequiredType, getProps) {
return Children.map(children, function(child) {
if (isValidElement(child) === false) {return child;}

if (isRequiredType(child)) {

return cloneElement(
child,
// Return new props
// {
// index, iterated in getProps closure
// focusRef, saved to `this.focusable` aswell, w/ index above
// }
getProps()
);
}

if (child.props.children) {
return cloneElement(child, {
children: recursivelyMapElementsOfType(child.props.children, isRequiredType, getProps)
});
}

return child;
});
}

export class ElementWithFocusManagement {
constructor(props) {
super(props);

// Map of all refs, that should receive focus
// {
// 0: {current: HTMLElement}
// ...
// }
this.focusable = {};
this.state = {
lastInteractionIndex: 0
};
}

handleKeyDown() {
// Handle arrow keys,
// check that element index in `this.focusable`
// update state if it is
// focus element
}

render() {
return (
<div onKeyDown={this.handleKeyDown}>
<Provider value={{lastInteractionIndex: this.state.lastInteractionIndex}}>
{recursivelyMapElementsOfType(
children,
isRequiredType, // Check for required `displayName` match
getProps(this.focusable) // Get index, and pass ref, that would be saved to `this.focusable[index]`
)}
</Provider>
</div>
);
}
}

with-focus.js

export function withFocus(WrappedComponent) {
function Focus({index, focusRef, ...props}) {
return (
<Consumer>
{({lastInteractionIndex}) => (
<WrappedComponent
{...props}

elementRef={focusRef}
tabIndex={lastInteractionIndex === index ? 0 : -1}
/>
)}
</Consumer>
);
}

// We will match for this name later
Focus.displayName = `WithFocus(${WrappedComponent.name})`;

return Focus;
}

Anything.js

const FooWithFocus = withFocus(Foo);

<ElementWithFocusManagement> // Like toolbar, dropdown menu and etc.
<FooWithFocus>Hi there</FooWithFocus> // Button, menu item and etc.

<AnythingThatPreventSimpleMapping>
<FooWithFocus>How it's going?</FooWithFocus>
</AnythingThatPreventSimpleMapping>

<SomethingWithoutFocus />
</ElementWithFocusManagement>

最佳答案

react-roving-tabindex看起来相当不错。

关于javascript - 带 React 的流动 tabindex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com