如何将组件中的 props 传递给 FlatList renderItem

How to pass props in the component to FlatList renderItem

我的组件中有一个函数作为道具,我必须将这个函数道具传递给 FlastList 中 renderItem 中的另一个组件。怎么做?这是我的代码。

import React, { Component } from 'react';
import { View } from 'native-base';
import PropTypes from 'prop-types';
import { FlatList } from 'react-native';
import AddPlayers from '../AddPlayers/AddPlayers';
import League from '../League/League';
export default class InviteLeagues extends Component {
  static propTypes = {
    invitedLeagues: PropTypes.Array,
    label: PropTypes.string.isRequired,
    InvitedLeaguesList: PropTypes.Array,
    onPress: PropTypes.func.isRequired
  };

  static defaultProps = {
    InvitedLeaguesList: [
      { name: 'Howdy', createdBy: 'email1@gamil.com', status: 'Join' },
      { name: 'Lorem', createdBy: 'email@gmail.com', status: 'Join' }
    ]
  };

  renderLeague(item) {
    return <League invitedLeague={item} />;
  }

  render() {
    return (
      <View {...this.props}>
        <AddPlayers
          label={this.props.label}
          labelStyle={{ fontStyle: 'italic' }}
        />
        <FlatList
          numColumns={1}
          data={this.props.InvitedLeaguesList}
          renderItem={this.renderLeague}
        />
      </View>
    );
  }
}

现在我必须将 onPress (Function Prop) 传递给 League Component

我这样试过

 <FlatList
          numColumns={1}
          data={this.props.InvitedLeaguesList}
          renderItem={this.renderLeague}
          extraData={this.props}
        />

renderLeague(item) {
    return <League invitedLeague={item} onPress={this.props.onPress} />;
  }

我想你试着做一个 callBack 函数, 如果是,请执行以下操作。

renderLeague(item) {
    return <League invitedLeague={item} onPress={this._callBack.bind(this)} />;
}


//callback function
_callBack(data) {
   // your code here...
}

来自你的组件League

调用如下函数,

this.props.onPress(datas);

这种方式适合我

<FlatList
     numColumns={1}
     data={this.props.InvitedLeaguesList}
     renderItem={({ item }) => <League invitedLeague={item} onPress={this.props.onPress} />}
     extraData={this.props}
 />

您可以将道具作为参数传递给呈现平面列表项的函数,如下所示:

<FlatList
     numColumns={1}
     data={this.props.InvitedLeaguesList}
     renderItem={(item) => this.renderLeague(item, this.props)}
/>

并且您可以在 renderLeague 函数中使用此参数:

renderLeague({item}, props) {
   ...
}

props 变量包含 props 的所有参数,您可以在其他地方使用 this.props