1.自动获取焦点
< TextInput
style= { {
width : 90 ,
paddingLeft : 20 ,
} }
autoFocus= { true }
onChangeText= { text => setText ( text) }
value= { text}
/ >
2.取消焦点
import React, { useRef } from 'react' ;
import { TextInput, Button} from 'react-native' ;
export default function App ( ) {
const inputRef = useRef ( null ) ;
const [ text, setText] = useState ( '' )
const btnClick = ( ) => {
inputRef. current. blur ( ) ;
}
return (
< TextInput
ref= { inputRef}
style= { {
width : 90 ,
paddingLeft : 20 ,
} }
onChangeText= { text => setText ( text) }
value= { text}
/ >
< Button
onPress= { btnClick}
>
)
}
3.监听键盘收起移除焦点
import React, { useRef } from 'react' ;
import { TextInput, Button, Keyboard} from 'react-native' ;
export default function App ( ) {
const inputRef = useRef ( null ) ;
const [ text, setText] = useState ( '' )
useEffect ( ( ) => {
const keyboardDidHideListener = Keyboard. addListener (
'keyboardDidHide' ,
( ) => {
console. log ( '键盘已隐藏' ) ;
inputRef. current. blur ( ) ;
}
) ;
return ( ) => {
keyboardDidHideListener. remove ( ) ;
} ;
} , [ ] ) ;
return (
< TextInput
ref= { inputRef}
style= { {
width : 90 ,
paddingLeft : 20 ,
} }
onChangeText= { text => setText ( text) }
value= { text}
/ >
)
}