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

React Native:不使用箭头函数与bind,为TouchableOpacity的onPress传参

解决方案:React Native TouchableOpacity 无箭头/ bind 传参实现

方案1:封装独立子组件(推荐)

将可点击条目抽为独立组件,通过 props 传递数据和回调,避免在父组件渲染时重复创建函数,同时利用 PureComponent 优化渲染性能。

父组件代码:

class OfferList extends React.Component {
  gotoOfferDetail(offerData: IOfferDetailItem) {
    console.log(offerData.title);
  }

  render() {
    return (
      <View>
        {this.state.offers.map(item => (
          <OfferItem
            key={item.id}
            item={item}
            onItemPress={this.gotoOfferDetail}
          />
        ))}
      </View>
    );
  }
}

子组件 OfferItem.js 代码:

import React from 'react';
import { TouchableOpacity, StyleSheet } from 'react-native';

class OfferItem extends React.PureComponent {
  handlePress = () => {
    this.props.onItemPress(this.props.item);
  };

  render() {
    return (
      <TouchableOpacity
        activeOpacity={0.9}
        style={styles.touchOfferItem}
        onPress={this.handlePress}
        accessibilityLabel={`Test`}
        testID={'Test'}
        accessible={false}
      >
        {/* 插入条目内容,如 {this.props.item.title} */}
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  touchOfferItem: {
    // 原有样式定义
  }
});

export default OfferItem;

handlePress 仅在组件实例化时绑定一次,不会随渲染重复创建,同时 PureComponent 会对比 props 变化,避免无意义重渲染。


方案2:预生成绑定函数映射(类组件适用)

在组件初始化/数据更新时,提前为每个条目生成对应的点击处理函数,存入实例变量中,渲染时直接复用。

class OfferList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { offers: [] };
    this.pressHandlers = {}; // 存储每个条目的处理函数
  }

  componentDidMount() {
    // 模拟获取数据
    const offers = this.getOfferData();
    this.setState({ offers }, () => {
      // 为每个条目生成绑定函数
      this.state.offers.forEach(item => {
        this.pressHandlers[item.id] = () => this.gotoOfferDetail(item);
      });
    });
  }

  // 数据更新时同步更新处理函数
  componentDidUpdate(prevProps, prevState) {
    if (prevState.offers !== this.state.offers) {
      this.pressHandlers = {};
      this.state.offers.forEach(item => {
        this.pressHandlers[item.id] = () => this.gotoOfferDetail(item);
      });
    }
  }

  gotoOfferDetail(offerData: IOfferDetailItem) {
    console.log(offerData.title);
  }

  render() {
    return (
      <View>
        {this.state.offers.map(item => (
          <TouchableOpacity
            key={item.id}
            activeOpacity={0.9}
            style={styles.touchOfferItem}
            onPress={this.pressHandlers[item.id]}
            accessibilityLabel={`Test`}
            testID={'Test'}
            accessible={false}
          >
            {/* 条目内容 */}
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}

该方案适合数据变动不频繁的场景,需注意在数据更新时同步维护处理函数映射。

内容的提问来源于stack exchange,提问作者Ila Nautiyal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:31:01