React Native多行TextInput空白行点击无法聚焦问题求助
解决多行TextInput点击灰色区域任意位置都聚焦的问题
这个问题我之前开发React Native项目时也碰到过!默认情况下,多行TextInput只有点击到文本内容或者占位符的区域才会唤起焦点,外层的灰色容器本身并不会触发TextInput的聚焦逻辑,咱们可以通过以下几步解决:
- 给TextInput添加一个
ref,方便我们手动调用它的聚焦方法 - 给包裹TextInput的灰色
View添加onPress事件,在事件回调里主动让TextInput获取焦点
修改后的完整代码
<ScrollView style={{ flex: 1}}> <View style = {Style.dropdownField}> <Dropdown label={'Motivo'} data={this.props.remiseExcusesData} value={this.state.remiseExcuses.value} onChangeText={(value,index, data)=> this.setState({remiseExcuses:data[index]})} /> </View> <View style = {{ height:150, marginHorizontal:20, backgroundColor:'#f9f9f9', marginTop:20}} onPress={() => this.textInputRef.focus()} // 添加点击事件,手动触发聚焦 > <TextInput ref={(ref) => this.textInputRef = ref} // 添加ref引用 style={Style.minitextInput} placeholder={'Escribir motivo'} textAlign={'left'} autoCorrect={false} autoCapitalize={'none'} underlineColorAndroid='transparent' multiline onChangeText={(text) => this.setState({motive:text}) } value={this.state.motive} onFocus={() => console.log('Fire only on tap')} /> </View> </ScrollView>
原理说明
外层的灰色View现在会响应整个区域的点击事件,当用户点击这个View的任何位置时,我们通过之前定义的ref调用TextInput的focus()方法,强制让它获取焦点,这样就能唤起键盘了。
另外如果你的minitextInput样式里有内边距(padding),也完全不影响,因为整个View的点击都会触发聚焦逻辑,覆盖所有灰色区域。
内容的提问来源于stack exchange,提问作者LeandroG
相关产品推荐
相关产品推荐

