TextInput 二三事
记录下这两天使用 TextInput 时遇到的问题及一些注意事项。
TextInput 键盘遮挡视图
- KeyboardAvoidingView
import { KeyboardAvoidingView, ScrollView } from 'react-native';
<View style={[styles.container]}>
<KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
<ScrollView
style={[styles.scrollViewStyle]}
keyboardShouldPersistTaps="handled"
>
// 视图布局
</ScrollView>
</KeyboardAvoidingView>
</View>
这里单纯的添加 KeyboardAvoidingView 只会移动 TextInput 的坐标,但输入框下面还有其他视图,为了不遮挡其他视图,在将整个布局放到
ScrollView 中。
TextInput 中一些需要注意的属性
某些属性 iOS 与 Android 的取值或展示样式的差异
TextInput 在安卓上默认有一个底边框,同时会有一些 padding。如果要想使其看起来和iOS上尽量一致,则需要设置padding: 0,同时设置
underlineColorAndroid="transparent"
来去掉底边框。
keyboardShouldPersistTaps 操作键盘
如果当前界面有软键盘,那么点击 scrollview 后是否收起键盘,取决于本属性的设置。(注意:很多人反应 TextInput 无法自动失去焦点/需要点击多次切换到其他组件等等问题,其关键都是需要将 TextInput 放到ScrollView中再设置本属性)
keyboardType 的不同取值,iOS 和 Android 不同之处
无法通过在 TextInput 标签中定义 ref 调用 clear( )
通过 ref 在 TextInput 标签中定义不同的引用类型,然后发现无法根据 定义的 ref 调用 TextInput 的 clear( ) 方法。
react-native info 为:
Environment:
OS: macOS High Sierra 10.13.6
Node: 8.6.0
Yarn: 1.12.3
npm: 5.3.0
Watchman: 4.9.0
Xcode: Xcode 10.1 Build version 10B61
Android Studio: 3.2 AI-181.5540.7.32.5014246
Packages: (wanted => installed)
react: 16.3.1
react-native: 0.55.3
代码如下:
export class LoginSceneComponent extends Component {
constructor(props) {
super(props)
this.codeTextInputRef = React.createRef()
}
changeLoginType = () => {
this.codeTextInputRef.current.clear()
}
render () {
return (
<ScrollView
style={[styles.scrollViewStyle]}
keyboardShouldPersistTaps="handled"
>
<TextInput
ref={this.codeTextInputRef}
style={[styles.inputStyle]}
secureTextEntry={this.state.loginTypeFlag}
value={this.state.passWord}
onChangeText={text => this.setState({ passWord: text })}
/>
</ScrollView>
)
}
}
最终通过在
onChangeText={txt => this.setState({ passWord: txt })}
方法中重新 setState 参数清除了输入框中内容。
注意: React 16.3 更新了 创建 Ref 的方法。
参考资料
facebook/react-native/issues/18843
facebook/react-native/issues/18272
–EOF–
若无特别说明,本站文章均为原创,转载请保留链接,谢谢!