gpt4 book ai didi

reactjs - 使用 react-simple-keyboard 正确处理 ref

转载 作者:行者123 更新时间:2023-12-05 03:55:38 27 4
gpt4 key购买 nike

我正在使用 react-simple-keyboard,并通过使用空字符串调用 useState Hook 的 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 on it),并在消费组件中使用 RSK 方法而不是键盘包装器。

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

解决这个问题的正确方法是什么?

更新:我试过 suggested solution但它不工作。我实际做的唯一改变是我没有在内部组件 (KeyboardElement) 中使用传递的 ref 并且我定义了一个 clearInput 函数在 KeyboardElement 上,它只是调用 its ref 的 clearInput 函数。但是消费组件中的 ref 始终是 undefined

我认为我的情况与其他情况的区别在于我没有调用 ref 的函数,而是调用了“嵌套 ref”的函数。我将 parent 的 ref 作为 prop 传递给 child ,以便 child 可以将 its ref 分配给该 prop,这似乎是错误的。

最佳答案

我使用 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}
/>

关于reactjs - 使用 react-simple-keyboard 正确处理 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60101381/

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