在RN版本0.44,長文本編輯,使用TextInput。
出現以下問題:
1:點選軟鍵盤中“回車”按鈕,軟鍵盤隐藏。
2:設定blurOnSubmit={false},點選軟鍵盤中“回車”按鈕,沒有換行。
3:TextInput設定高度,文字預設是居中顯示。設定高度自增長,有閃爍。
根據問題來一步步解決
實作效果
1:點選軟鍵盤中“回車”按鈕,軟鍵盤隐藏。
blurOnSubmit 強制設為 false 、
2:設定blurOnSubmit={false},點選軟鍵盤中“回車”按鈕,沒有換行。
正常情況下,對于 multiline 設定為 true 的 TextInput,
按下回車,應該會觸發 onChange 和 onChangeText 事件;
但是在 Android 下使用中文輸入法時,
觸發的是 onSubmitEditing 和 onEndEditing 事件。
把 blurOnSubmit 強制設為 false
這樣可以避免按回車時 input blur
但會變成連着觸發兩次 onSubmitEditing,不再觸發 onEndEditing。
3:TextInput設定高度,文字預設是居中顯示。設定高度自增長,有閃爍。
這裡使用以下方法來解決這個問題
style={{
height: DP.dp185,
width: width,
fontSize: fontSize,
textAlignVertical: 'top',//重點
color:'#333333',
}}
最後貼代碼
'use strict';
import React, {Component, PropTypes} from "react";
import {
TextInput,//輸入框
Dimensions,
Platform,
} from "react-native";
//螢幕寬度,高度 screen(scale為分辨率)
let {width, height} = Dimensions.get('window');
export default class FixedTextInput extends Component {
// 構造
constructor(props) {
super(props);
// 初始狀态
this.state = {
feedBackText: "",
selection: {start: 0, end: 0},
};
this.onChange = this._onChange.bind(this);
}
_latestSubmitEditing = null
_fixedOnSubmitEditing = e => {
// 實作隻響應第一次 onSubmitEditing 事件
const latestSubmitEditing = this._latestSubmitEditing
this._latestSubmitEditing = e.timeStamp
if (latestSubmitEditing && e.timeStamp - latestSubmitEditing < 200) return
let value = this.state.feedBackText;
let length = this.state.feedBackText.length;
let {start, end} = this.state.selection;
if (end >= 0 && length >= end) {
let valueBefore = value.substring(0, end)
let valueAfter = value.substring(end, length)
this.setState({
feedBackText: valueBefore + "\n" + valueAfter,
})
if (end != length) {
const newSelection = {
start: start + 1,
end: end + 1
}
//重新定位光标位置
this.setState({
selection: newSelection
})
}
}
}
_onChange(changeText) {
this.setState({
feedBackText: changeText,
});
}
_isNull(str) {
if (str === "" || str === undefined) return true;
let regu = "^[ ]+$";
let re = new RegExp(regu);
return re.test(str);
}
//selection={selection} 設定光标位置
//onSelectionChange 儲存目前光标位置
//onSubmitEditing 點選回車按鈕的回調函數
render() {
let {feedBackText, selection} = this.state;
return (<TextInput
selection={selection}
onSelectionChange={this._onSelectionChange}
onChangeText={this.onChange}
value={feedBackText}
{...this.props}
multiline={true}
onSubmitEditing={this._fixedOnSubmitEditing}
blurOnSubmit={false}/>);
}
_onSelectionChange = (event) => {
this.setState({selection: event.nativeEvent.selection})
}
}
使用
<View style={{
height: DP.dp185,
marginTop: DP.dp17,
backgroundColor: 'white',
}}>
<FixedTextInput
style={{
height: DP.dp185,
width: width,
fontSize: fontSize,
textAlignVertical: 'top',
color:'#333333',
}}
placeholder={placeholder}
placeholderTextColor={"#999999"}
underlineColorAndroid="transparent"
maxLength={200}
numberOfLines={8}
/>
</View>
轉載自
https://blog.csdn.net/cjw8990/article/details/79292341