我有以下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
,但由于这是在类定义之外定义的,因此我看不到我有权访问这些属性。如何完成上述代码尝试的操作?
答案 0 :(得分:3)
您可以将回调传递给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) => 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>
);
}
}