键盘快捷键在Web应用程序中管理有点棘手.
考虑一个Widget组件.
我希望能够集中某些元素,并基于键盘shorcuts在此组件上运行函数.
class Widget extends React.Component {
componentDidMount() {
this.setBindings()
},
componentWillUnmount() {
this.removeBindings();
}
}
Run Code Online (Sandbox Code Playgroud)
setBindings和removeBindings将使用像mousetrap这样的库来绑定特定的键盘快捷键
现在,上述解决方案存在两个问题:
Widget.这破坏了代码的"粒度" - 理想情况下,用户应该能够使用Widget,然后使用WidgetWithShortcuts,或类似的东西另一个可能的解决方案是传递一个实例
const widgetShortcuts = (widgetInstance) => {
return {
'ctrl i': () => widgetInstance.focusInput(),
}
}
Run Code Online (Sandbox Code Playgroud)
第二种解决方案的问题是:
widgetInstance必须公开许多可公开访问的方法,如focusSomeThing或invokeProp等
如果Widget想要一些工具提示,在某些地方显示键盘快捷键,键盘shorcuts的信息将在不同的地方重复.可以在一个地方更改快捷方式,而在其他地方忘记这样做
是否有最佳实践或关于如何通过上述问题的解决方案实现键盘快捷键的一些想法?
React-hotkeys不是一种方法,而是一个听起来可以解决您面临的问题的工具。
<HotKeys>附加有热键的自定义组件中来使用它。keymap&分配给热键handler我使用这个插件面临的一个问题是,似乎没有一种方法可以阻止在输入字段中键入内容时触发热键,但除此之外,它似乎工作得很好。
我认为最好的选择是在顶层设置一次键盘快捷键侦听器,并将信息传递给可能或可能不关心快捷方式发生的组件。这解决了问题 1,您可以多次绑定侦听器,并且这也消除了公开任何组件函数的需要。
class ShortcutProvider extends Component {
state = { shortcut: null }
componentDidMount() {
// shortcut library listener
onShortcut(shortcut => this.setState({ shortcut })
}
render() {
<App shortcut={this.state.shortcut} />
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的小部件可以对 prop 的更改做出反应(或不反应):
class Widget extends Component {
...
componentWillReceiveProps(nextProps) {
if (this.state.shouldReactToShortcut) {
if (nextProps.shortcut === 'ctrl i') {
// do something
}
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果您将快捷方式属性传递给许多组件,那么将快捷方式状态放入上下文中可能是值得的。