从类定义之外调用React函数PropType



我有以下React组件。。

import React, { Component,PropTypes } from 'react';
import RequestListItem from '../RequestListItem';
import { ScrollView,Text,View } from 'react-native';
class  RequestList extends Component {

  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map(mapRequests)}
      </ScrollView>
    );
  }
}
RequestList.propTypes = {
  requests: PropTypes.array.isRequired,
  onRequestItemClick: PropTypes.func.isRequired
};
var mapRequests = (request, i) => {
  <RequestListItem
      id={request.id}
      title={request.title}
      onRequestItemClick={this.props.onRequestItemClick.bind(this)}
  />
};
export default RequestList;

我遇到的问题与mapRequest函数有关。我需要能够调用作为属性传递给该组件的onRequestItemClick,但由于这是在类定义之外定义的,所以我似乎无法访问这些属性。我该如何完成上面的代码所要做的工作?

您可以将回调传递给mapRequests方法,而不是尝试直接从props:中提取它

class RequestList extends Component {
  constructor(props) {
      super(props);
      this.props.onRequestItemClick = this.props.onRequestItemClick.bind(this) // I'm not sure why your binding to this something you got from the props, so consider removing this line
  }
  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map((request) => mapRequests(request, this.props.onRequestItemClick))} // the arrow function calls mapRequest, and passes the request and the callback 
      </ScrollView>
    );
  }
}
var mapRequests = (request, onRequestItemClick) => {
  <RequestListItem
      id={request.id}
      title={request.title}
      onRequestItemClick={onRequestItemClick}
  />
};

但是,如果您已经使用了匿名函数,那么无论如何都不需要mapRequests函数:

class RequestList extends Component {
  constructor(props) {
      super(props);
      this.props.onRequestItemClick = this.props.onRequestItemClick.bind(this) // I'm not sure why your binding to this something you got from the props, so consider removing this line
  }
  render(){
    return (
      <ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        automaticallyAdjustContentInsets={false}
        scrollEventThrottle={200}>
        {this.props.requests.map((request) => (
            <RequestListItem
                id={request.id}
                title={request.title}
                onRequestItemClick={this.props.onRequestItemClick}        
            />
        )}
      </ScrollView>
    );
  }
}

相关内容

  • 没有找到相关文章

最新更新