bind方法解决this作用域问题

在JavaScript中this是有作用域的,先看代码

import React, {
    Component
} from 'react';

import {
    StyleSheet,
    View,
    Text,
    ListView,
    TouchableHighlight,
    Alert,
} from 'react-native';

class IndexView extends Component {
    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 != r2
        });
        this.state = {
            dataSource: ds.cloneWithRows([
                '1111111', '222222', '333333', '444444', '555555', '666666', '777777', '888888', '999999', '000000', '123457',
            ])
        };
        this._renderRow = this.renderRow.bind(this);
        this._renderSeparator = this.renderSeparator.bind(this);
        this._rowPressed = this.rowPressed.bind(this);
    }
    render() {
        return (
            <ListView
              style={{flex:1, backgroundColor: 'white',}}
              dataSource={this.state.dataSource}
              renderRow={this._renderRow}
              renderSeparator = {this._renderSeparator}
             />
        );
    }
    renderRow(rowData,sectionID,rowID,highlightRow) {
        return (
            <TouchableHighlight
              onPress={() => {
                    this._rowPressed(sectionID, rowID);
                    highlightRow(sectionID, rowID);
                }
              }
              style={{}}
              underlayColor='red'>
                <View style={{flexDirection: 'row',justifyContent: 'center',backgroundColor: '#F6F6F6',}}>
                    <Text  style={{fontSize: 18}}>
                        {rowData}
                    </Text>
                </View>
            </TouchableHighlight>

        );
    }
    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return(
            <View key={`${sectionID}-${rowID}-renderSeparator`} style={{flex:1, height: .5,backgroundColor: '#c0c0c0'}}>
            </View>
        );
    }

    rowPressed(sectionID,rowID) {
        Alert.alert('标题','内容');
    }
}

const styles = StyleSheet.create({

});


export default IndexView; 

renderRow方法内部用到了this,其实renderRow这个方法的调用者是ListView这个类,那么在renderRow内部的this就不在是当前你所需要的this了,解决方法就是在初始化的时候bind,其他几个方法同理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值