gpt4 book ai didi

javascript - 如何在 React Native 中转发其 ref 的组件中使用 Ref

转载 作者:行者123 更新时间:2023-12-05 01:58:38 24 4
gpt4 key购买 nike

我有一个 React native 自定义输入组件,我已成功将其引用转发给父组件。现在,我还想引用 child 本身的输入,我该怎么做??

//my imports here

//my text field component
export const MyTextField = React.forwardRef((props, ref) => {

const [inputValue, setValue] = useState('');

const clearInput = () => {
setValue("");
//I want to get the input by ref here and apply "clear()" method on it
}


return (
<View>
<TextInput
/*
How can i also use this ref to refer to this textinput in The "clearInput" function above
*/
ref={ref}
value={inputValue}
onChangeText={(value) => setValue(value)}
{...props}
/>
<IconButton
icon="close-circle"
onPress={clearInput}
/>
</View>
);
});

最佳答案

Travis Waith-Mair 的这篇文章显示了您想对细节做什么:https://non-traditional.dev/how-to-use-the-forwarded-ref-in-react-1fb108f4e6af

还有一个 npm 包:https://www.npmjs.com/package/@bedrock-layout/use-forwarded-ref


这里有一些例子:https://snack.expo.io/@truetiem/use-forwardedref

如果您想将其实现到您的代码中:

// Copy-Pasted the "useForwardedRef" from the linked article by "Travis Waith-Mair"
const useForwardedRef = (ref) =>{
const innerRef = useRef(null);

useEffect(() => {
if (!ref) return;
if (typeof ref === 'function') {
ref(innerRef.current);
} else {
ref.current = innerRef.current;
}
});

return innerRef;
}

export const MyTextField = React.forwardRef((props, ref) => {
// passing the ref to useForwardedRef hook
const forwardedRef = useForwardedRef(ref);
const [inputValue, setValue] = useState('');

const clearInput = () => {
setValue("");

// You can access the ref safely with forwardedRef
forwardedRef.current?.clean();
}


return (
<View>
<TextInput
// Passing the forwardedRef here
ref={forwardedRef}
value={inputValue}
onChangeText={(value) => setValue(value)}
{...props}
/>
<IconButton
icon="close-circle"
onPress={clearInput}
/>
</View>
);
});

关于javascript - 如何在 React Native 中转发其 ref 的组件中使用 Ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68422528/

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