从anon函数中访问类范围

时间:2016-05-29 21:02:02

标签: reactjs react-native jsx

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>
        );
    }

我正在尝试从匿名函数中控制日志类的状态,并且我得到了未定义。我必须绑定范围吗?我试过没有成功。

1 个答案:

答案 0 :(得分:-1)

使用_renderRow = (rowData) => { return ( <View key = { rowData.id } > <TouchableHighlight onPress={ () => console.log(this.state) }> { Registry.render(rowData) } </TouchableHighlight> </View> ); } lambda函数提供此词法绑定。更改函数的代码如下:

Eclipse