【问题标题】:Touchable Opacity onPress not able to call function - scoping issue?Touchable Opacity onPress 无法调用函数 - 范围问题?
【发布时间】:2019-02-24 20:25:58
【问题描述】:

我正在使用 React Native 进行开发。

我有一个渲染项目的FlatList。我添加了TouchableOpacity 并想在按下该项目时调用一个函数,但该函数没有被调用。

当我点击该项目时,我得到一个错误 找不到变量:_onPress

我认为这是范围界定的问题。有人可以向我解释发生了什么问题吗?

我想第二个问题是:我的_onPressconsole.log 会像我一样通过传递道具来记录项目名称吗?

export default class ModalScreen extends React.Component {
//..

        _onPress = (item) => {
           console.log('Clicked:' + item)
        };

      renderItem({ item }) {
        return (
          <TouchableOpacity onPress={() => this._onPress(item)}>
            <View>
              <Text>{item.name}</Text>
            </View>
          </TouchableOpacity>
        )
      }



render() {  
    return (
    //..
          <View style={{flex: 2, backgroundColor: '#FFF', flexDirection:'row'}} >
                <FlatList
                data={this.state.searchedItems}
                renderItem={this.renderItem}
                />
            </View>

    //..

【问题讨论】:

    标签: javascript reactjs react-native scope


    【解决方案1】:

    尝试用这个 'renderItem = ({ item }) => {

    改变这个 'renderItem({ item }) {'

    【讨论】:

    • 传奇!谢谢你。你能解释一下那里发生了什么吗?那有什么不同呢?它唯一不做的就是接受 item 道具和 console.log 它。目前它记录“点击未定义”。你能帮忙吗?
    • 这是因为当你提供你的 renderItem 函数时,范围发生了变化,所以在 renderItem 函数中这指的是 TouchableOpacity 实例
    • 但是添加箭头函数有什么帮助呢?箭头函数的作用是不同的。抱歉,我需要快速了解箭头功能等。
    • 箭头函数没有这个作用域,当你在类中用箭头函数声明函数时,它总是引用类的当前实例
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多