react-native - 自动焦点属性在 React Native 的文本输入组件中不起作用
问题描述
我正在制作一个搜索栏,我希望他们在单击搜索按钮后打开键盘,但是 TextInput 的 autoFocus 属性不起作用。我究竟做错了什么?
这是代码:
const SearchBar = () => {
return (
<View style={{ flex: 1 }}>
<TextInput placeholder="Search"
style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1,
borderRadius: 20 }}
autoFocus={true}
/>
</View>
)
}
const Search = () => {
return (
<TouchableWithoutFeedback onPress={()=>Keyboard.dismiss()} >
<SearchBar />
</TouchableWithoutFeedback>
)
}
解决方案
嗯,理想情况下,autoFocus 应该可以安装这个 comp。
如果不是,解决方法是显式添加一个 ref 并聚焦它
class ABC extends .. {
constructor(props){
...
this.textInput = React.createRef();
}
componentDidMount(){
this.textInput.current.focus();
}
SearchBar = () => {
return (
<View style={{ flex: 1 }}>
<TextInput placeholder="Search"
style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1,
borderRadius: 20 }}
autoFocus={true}
ref={this.textInput}
/>
</View>
)
}
}
推荐阅读
- java - Firebase 数据不会加载到我的 RecyclerView 中
- r - 按纬度或经度将地图拆分为两个单独的地图
- flutter - pushAndRemoveUntil后android的后退按钮不工作
- node.js - 当我在 MERN 中提交数据时出现错误 400(错误请求)
- node.js - 来自节点的 Onclick 函数 pug
- java - 自定义声明样式不显示文本属性
- swift - 如何在 SwiftUI 中使用径向渐变填充路径
- android - 当数据绑定android中的数据发生变化时如何更新UI?
- javascript - 教师变焦考勤工具
- google-cloud-platform - 如何解释 Google Cloud Natural Language API 情绪分析输出?