【问题标题】:Access class scope from within anon function从 anon 函数中访问类范围
【发布时间】:2016-09-27 15:38:29
【问题描述】:
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>
        );
    }

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

【问题讨论】:

    标签: reactjs react-native jsx


    【解决方案1】:

    使用=&gt; lambda 函数来提供 this 的词法绑定。修改你的函数代码如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2016-08-13
      • 2015-02-06
      • 1970-01-01
      • 2021-04-23
      • 2016-04-04
      • 2021-12-30
      相关资源
      最近更新 更多