使用反应简单的键盘正确处理参考



我正在使用react-simple-keyboard,并且通过使用空字符串调用useState钩子的setter来清除我的输入会清除输入,但不会清除键盘的"内存",因此下次键入时,您将再次添加到旧字符串中。

react-simple-keyboard(RSK(有一个可以解决问题的clearInput函数,并且(据我了解(必须在keyboardRef上调用它。所以我把它装了起来:

我的键盘组件(包装器(

export default KeyboardElement = ({ onChange, keyboardRef }) => {
return <KeyboardContainer>
<Keyboard
layout={ {
'default': [
'1 2 3 4 5 6 7 8 9 0',
'Q W E R T Y U I O P',
'A S D F G H J K L',
'Z X C V B N M {bksp}',
],
} }
theme={ 'firmm-keyboard' }
keyboardRef={ keyboardRef }
onChange={ onChange }
/>
</KeyboardContainer>;
};

消耗组件

export default LicenseEntry = ({ onClose }) => {
const [text, setText] = useState('');
const keyboard = useRef();
const onClear = () => {
// @ts-ignore
keyboard.current!.clearInput();
setText('');
};
return (
<FullScreenModalBackground zIndex={ 9 }>
<OuterContainer>
<InnerContainer>
<ExitButton onClose={ onClose }/>
<HeaderText>Add license</HeaderText>
<Input
readOnly
data-testid="LICENSE_INPUT"
value={ formatLicense(text) }
placeholder={ 'type license here' }
/>
<KeyboardElement
keyboardRef={ r => keyboard.current = r }
onChange={ setText }
/>
<Button>Submit</Button>
<Button onClick={ onClear }>Clear</Button>
</InnerContainer>
</OuterContainer>
</FullScreenModalBackground>
);
};

这有效,但有代码异味:我在消费组件中创建 ref(然后将其传递给我的键盘包装器,以便 RSK 可以使用它,并且可以调用clearInput(,并在消费组件中使用 RSK 方法而不是键盘包装器。

使用键盘的组件应该使用并了解 RSK 的引用似乎是错误的。这也意味着消费组件中的keyboard.current!类型是never(或其他一些无法管理的类型(,所以我使用@ts-ignore作为创可贴。

正确的方法是什么?

更新:我已经尝试了建议的解决方案,但它不起作用。我实际做的唯一更改是我没有在内部组件(KeyboardElement(中使用传递的ref,而是在KeyboardElement上定义了一个clearInput函数,该函数仅调用ref的clearInput函数。但是消费组件中的引用始终是undefined.

我认为我的情况和另一个情况之间的区别在于我不是在调用 ref 的函数,而是在调用"嵌套 ref"的函数。我将父母的 ref 作为道具传递给孩子,以便孩子可以将其ref 分配给该道具,这似乎是错误的。

我在 3.1.9 版中使用它的方式是也导入KeyboardReactInterface

import Keyboard, { KeyboardReactInterface } from 'react-simple-keyboard'
const keyboardRef = useRef<KeyboardReactInterface | null>(null)
<Keyboard
keyboardRef={(r) => (keyboardRef.current = r)}
onChange={onChange}
onKeyPress={onKeyPress}
layoutName={layoutName}
/>

最新更新