You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在按下TouchableHighlight时立即获取其从数组赋值的数据?

Fix: Get Array Item Data Immediately on TouchableHighlight onPress

Hey David, let's sort out this TouchableHighlight issue you're hitting—it's a super common gotcha when working with list components in React Native, so I’ve got a few straightforward solutions for you.

The root problem almost always boils down to how you're passing (or not passing) the array item to your onPress handler. If you're seeing stale data or not getting the right item at all, it's usually because of a closure quirk or incorrect function binding. Here's how to fix it:

1. Pass the Item Directly in an Arrow Function (Most Intuitive)

When rendering your TouchableHighlight components inside a map() loop, wrap your onPress handler in an arrow function that explicitly passes the current array item. This ensures you get the exact item that was clicked, immediately.

import React from 'react';
import { View, TouchableHighlight, Text } from 'react-native';

const MyListComponent = () => {
  // Example array of data
  const myData = [
    { id: 1, title: 'First Item', value: 'foo' },
    { id: 2, title: 'Second Item', value: 'bar' },
    { id: 3, title: 'Third Item', value: 'baz' },
  ];

  // Handler that receives the selected item
  const handleItemPress = (selectedItem) => {
    // You'll have immediate access to the item's data here!
    console.log('Clicked item:', selectedItem);
    // Do your logic here—update state, navigate, etc.
  };

  return (
    <View>
      {myData.map((item) => (
        <TouchableHighlight
          key={item.id} // Always use a unique key (avoid index if possible)
          onPress={() => handleItemPress(item)}
          underlayColor="#e0e0e0"
          style={{ padding: 16, borderBottomWidth: 1, borderColor: '#eee' }}
        >
          <Text>{item.title}</Text>
        </TouchableHighlight>
      ))}
    </View>
  );
};

export default MyListComponent;

Pro tip: Use the item's unique id as the key instead of the array index—this helps React render the list more efficiently, especially if your array changes over time.

2. Use Curried Functions (For Reusable Logic)

If you want to define your handler with pre-bound logic (like setting a state value), you can use a curried function. This creates a new function for each list item that already has the item data baked in:

const handleItemPress = (selectedItem) => () => {
  console.log('Selected item data:', selectedItem);
  // Example: Update state with the selected item
  // setSelectedItem(selectedItem);
};

// In your map() render:
<TouchableHighlight
  key={item.id}
  onPress={handleItemPress(item)}
>
  <Text>{item.title}</Text>
</TouchableHighlight>

This works because handleItemPress(item) returns a new function that remembers the selectedItem value from the current iteration.

3. Fix Binding for Class Components

If you're still using class-based React Native components, make sure your handler is properly bound to the component instance, and pass the item explicitly:

import React, { Component } from 'react';
import { View, TouchableHighlight, Text } from 'react-native';

class MyClassList extends Component {
  state = {
    selectedItem: null,
  };

  // Use an arrow function to auto-bind `this`
  handleItemPress = (selectedItem) => {
    this.setState({ selectedItem });
    console.log('Pressed item:', selectedItem);
  };

  render() {
    const { myData } = this.props;
    return (
      <View>
        {myData.map((item) => (
          <TouchableHighlight
            key={item.id}
            onPress={() => this.handleItemPress(item)}
            underlayColor="#ccc"
          >
            <Text>{item.title}</Text>
          </TouchableHighlight>
        ))}
      </View>
    );
  }
}

export default MyClassList;

Common Mistake to Avoid

Don't try to reference the array item directly in a handler that's defined outside the map() loop—this will almost always lead to stale data or undefined values. For example, this won't work:

// ❌ Wrong! `item` here won't be the clicked item
const handlePress = () => {
  console.log(item);
};

{myData.map(item => (
  <TouchableHighlight onPress={handlePress}>
    <Text>{item.title}</Text>
  </TouchableHighlight>
))}

Wrap-Up

All these methods ensure that when the user presses the TouchableHighlight, you get the exact array item associated with that component immediately. Pick the approach that fits your code style best—most developers start with the first method since it's the easiest to read and debug.

内容的提问来源于stack exchange,提问作者David Futera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:51:28