react native 仿微信朋友圈的評論自動定位
constructor(props) { //es6 構造方法
super(props);
this.rowlayouts=[];
this.scrollview = null;
this.scrollview1 = null;
this.state = {
};
}
componentWillMount () { //將要加載控件
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
}
componentWillUnmount () { //將要銷燬控件
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow (e) { //當鍵盤彈出的時候要做的事
this.key=
e.startCoordinates.height //拿到的值就是鍵盤的高度
UIManager.measureInWindow( //當前listview在屏幕的位置
React.findNodeHandle(that.scrollview1),
(sx, sy, sw, sh) => {
var showIndex = 19; //listview 裏面item的個數
var itemHeight = 0;
for (var i = 0; i <= showIndex; ++i) {
if (that.rowlayouts[i]) {
itemHeight += that.rowlayouts[i].height;
}
}
// 36是輸入框的高度
var offset = Dimensions.get('window').height - sy - this.key-36; var newpos = itemHeight - offset; that.scrollview.scrollTo({x: 0, y: newpos}); });
var newpos = itemHeight - offset; that.scrollview.scrollTo({x: 0, y: newpos}); });}
_keyboardDidHide (e) { //當鍵盤收縮的時候要做的事
alert('Keyboard Hidden');
}
componentDidMount() {
}
<ListView
dataSource={this.state.ds1} //數據源,你可以自己定
renderRow={this._renderRow12.bind(this)} //單個的item
ref={(r) => this.scrollview1 = r} // 當控件被創建後將ScrollView這個對象的引用就傳給了 this.scrollview1 這個變量
/>
_renderRow12(rowData, sectionID, rowID){
return(
<TouchableOpacity
onLayout={(e) => this.rowlayouts[rowID] = e.nativeEvent.layout} //得到每一個一個對象數組(每個 對象裏面包含當前對象組件的度)
style={styles.column}
/>
)
}