我正在構建一個基于 react native 的應用程式,并且正在嘗試在“react-native-elements”庫中的輸入元素上設定一個參考。
我收到以下錯誤:
Type 'HTMLInputElement | null' is not assignable to type 'Ref<TextInput> | undefined'.
Type 'HTMLInputElement' is not assignable to type 'Ref<TextInput> | undefined'.
Property 'current' is missing in type 'HTMLInputElement' but required in type 'RefObject<TextInput>'.ts(2322)
index.d.ts(89, 18): 'current' is declared here.
index.d.ts(140, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & TextInputProps & RefAttributes<TextInput> & { containerStyle?: StyleProp<ViewStyle>; ... 15 more ...; renderErrorMessage?: boolean | undefined; } & Partial<...>'
我的代碼如下:
...
import { useState, useRef } from 'react'
import { Input } from 'react-native-elements'
export default function PublishRecipeScreen({ navigation }: RootTabScreenProps<'Publish a recipe'>) {
const ingredientInput = useRef<null | HTMLInputElement>(null)
const stepInput = useRef<null | HTMLInputElement>(null)
return (
<SafeAreaView>
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>Ingredients:</Text>
{recipeIngredients ? recipeIngredients.map((item, i) => <p key={i}>{item}</p>) : null}
<Input
inputContainerStyle={styles.textInput}
placeholder='Ingredient ...'
errorStyle={{ color: 'red' }}
errorMessage={formHasErrors && !recipeIngredients ? 'Please provide the recipe ingredients' : undefined}
onChangeText={(text: string) => setIngredient(text)}
multiline = {true}
ref={ingredientInput.current}
/>
<TouchableOpacity onPress={() => {
setRecipeIngredients([... recipeIngredients, ingredient])
setIngredient('')
}}>
<Text>New ingredient</Text>
</TouchableOpacity>
<Text style={styles.title}>Recipe:</Text>
{recipeSteps ? recipeSteps.map((item, i) => <p key={i}>{item}</p>) : null}
<Input
inputContainerStyle={styles.textInput}
placeholder='Recipe step ...'
errorStyle={{ color: 'red' }}
errorMessage={formHasErrors && !recipeSteps ? 'Please provide the recipe steps' : undefined}
onChangeText={(text: string) => setStep(text)}
multiline = {true}
ref={stepInput}
/>
...
我查找了元素定義,如下所示:
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P> | undefined;
contextTypes?: ValidationMap<any> | undefined;
defaultProps?: Partial<P> | undefined;
displayName?: string | undefined;
}
我嘗試將其用作 ref 型別,但也沒有用。我應該使用什么作為 ref 型別或者我怎么能弄清楚它?
完整代碼可以在這里找到:https ://github.com/coccagerman/mixr
謝謝!
uj5u.com熱心網友回復:
您的 TextInput refs 不是HTMLInputElements,它們是TextInputs。也許你習慣于從 web React 中以這種方式輸入它們。它們在 React Native 中是不同的。
代替
const ingredientInput = useRef<null | HTMLInputElement>(null)
const stepInput = useRef<null | HTMLInputElement>(null)
嘗試
const ingredientInput = useRef<null | TextInput>(null)
const stepInput = useRef<null | TextInput>(null)
一般來說,您可以嘗試使用 Typescript 錯誤訊息中的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433660.html
上一篇:反應本機文本輸入參考打字稿
