react-native-paper TextInput的ref属性未注册,如何添加该属性?
如何给 react-native-paper 的 TextInput 添加 ref 属性
react-native-paper 的 TextInput 是封装过的组件,不能直接用原生输入框的 ref 写法,以下是两种场景下的正确实现:
函数组件(使用 useRef)
根据需求选择获取组件实例或内部原生输入框实例:
方式1:获取 react-native-paper TextInput 组件实例
import React, { useRef } from 'react'; import { TextInput } from 'react-native-paper'; const LocationSearchInput = () => { const paperInputRef = useRef(null); const focusInput = () => { paperInputRef.current?.focus(); }; return ( <TextInput ref={paperInputRef} label="搜索位置" mode="outlined" /> ); }; export default LocationSearchInput;
方式2:获取内部原生 TextInput 实例
如果需要调用原生输入框的底层方法(比如clear()),使用inputRef属性:
import React, { useRef } from 'react'; import { TextInput } from 'react-native-paper'; const LocationSearchInput = () => { const nativeInputRef = useRef(null); const clearInput = () => { nativeInputRef.current?.clear(); }; return ( <TextInput inputRef={nativeInputRef} label="搜索位置" mode="outlined" /> ); }; export default LocationSearchInput;
类组件(使用 createRef)
类组件中用createRef配合对应属性实现:
获取组件实例
import React, { Component } from 'react'; import { TextInput } from 'react-native-paper'; class LocationSearchInput extends Component { constructor(props) { super(props); this.paperInputRef = React.createRef(); } focusInput = () => { this.paperInputRef.current?.focus(); }; render() { return ( <TextInput ref={this.paperInputRef} label="搜索位置" mode="outlined" /> ); } } export default LocationSearchInput;
获取原生输入框实例
import React, { Component } from 'react'; import { TextInput } from 'react-native-paper'; class LocationSearchInput extends Component { constructor(props) { super(props); this.nativeInputRef = React.createRef(); } clearInput = () => { this.nativeInputRef.current?.clear(); }; render() { return ( <TextInput inputRef={this.nativeInputRef} label="搜索位置" mode="outlined" /> ); } } export default LocationSearchInput;
注意事项
- 确保使用的 react-native-paper 版本为较新版本,旧版本可能存在
ref/inputRef支持不全的问题 - TypeScript 环境下需给 ref 指定对应类型,例如
const paperInputRef = useRef<TextInput>(null);
内容的提问来源于stack exchange,提问作者chackerian
相关产品推荐
相关产品推荐

