从匿名函数中访问 class 范围

Access class scope from within anon function

export default class A extends Component {

    constructor(props) {
        super(props)
        this.state = {
           items: Items
        }
    }

    componentWillMount() {
        var ds = new ListView.DataSource({
            rowHasChanged: (r1,r2) => r1 !== r2
        });

        this.dataSource = ds.cloneWithRows(this.state.items);
    }

    _renderRow(rowData) {
        return (
            <View key = { rowData.id } >
                <TouchableHighlight
                    onPress={ () => console.log(this.state) }>
                    { Registry.render(rowData) }
                </TouchableHighlight>
            </View>
        );
    }

我正在尝试从匿名函数中控制台记录 class 的状态,但我未定义。我必须绑定范围吗?我试过没有成功。

使用 => lambda 函数提供 this 的词法绑定。如下更改您的函数代码:

_renderRow = (rowData) => {
    return (
        <View key = { rowData.id } >
            <TouchableHighlight
                onPress={ () => console.log(this.state) }>
                { Registry.render(rowData) }
            </TouchableHighlight>
        </View>
    );
}