例如,在 中react-native,我可以將 ref 傳遞給常規TextInput,然后通過此 ref 呼叫方法:
const inputRef = useRef(null);
const myCallback = () => {
inputRef?.current?.focus();
}
<>
<TouchableOpacity onPress={() => myCallback()}>
<Text>
Press here to focus the input!
</Text>
</TouchableOpacity>
<TextInput
ref={inputRef}
{...props} // Doesn't matter, nothing special
>
</>
所以,我的問題是,如何在我的組件上創建方法,以便我可以使用 ref 從組件外部呼叫它們。
當然,我對在功能組件中創建方法很感興趣。
uj5u.com熱心網友回復:
您可以使用useImperativeHandle鉤子公開輸入元素所需的方法。
像這樣嘗試。
import React, { useImperativeHandle, forwardRef, useRef } from "react";
import { Button, StyleSheet, View, TextInput } from "react-native";
const MyTextInput = (props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
doFocus: () => {
inputRef.current.focus();
},
doBlur: () => {
inputRef.current.blur();
}
}));
return <TextInput ref={inputRef} style={props.style} />;
};
const MyCustomTextInput = forwardRef(MyTextInput);
const App = () => {
const myInputRef = useRef();
return (
<View style={styles.app}>
<MyCustomTextInput ref={myInputRef} style={styles.input} />
<View style={styles.button}>
<Button
onPress={() => {
myInputRef?.current?.doFocus();
}}
title="focus"
style={styles.button}
/>
</View>
<View style={styles.button}>
<Button
onPress={() => {
myInputRef?.current?.doBlur();
}}
title="blur"
style={styles.button}
/>
</View>
</View>
);
};
代碼沙箱 => https://codesandbox.io/s/react-native-web-forked-mnwee?file=/src/App.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/359557.html
上一篇:通過https://localhost:8000/訪問時,Localhost拒絕在WSL2上連接,但在使用內部WSLIP地址時有效
