我刚刚开始围绕React Native,并使用Redux管理state
,我的UI组件NativeBase library和react-native-router-flux处理视图之间的导航。
目前我正在构建一个基于guest
个对象数组创建的基本列表。该列表存储在Redux存储中,我可以访问它并相应地显示。列表中的每个项目都与guest
数组中的guests
相关联。我想让列表中的每个项目都可触摸,然后将相关的guest
对象作为属性传递给下一个视图以显示详细信息。
为此,我使用onPress
函数,该函数是与ListItem
组件关联的标准函数(请参阅NativeBase docs here)。我还为react-native-router-flux
跟踪了the documentation,并在组件本身之外定义了导航操作,以便ListItem
在按下时调用它而不是每次渲染时调用它。
我的问题是,我发现每次呈现onPress={goToView2(guest)}
时都会调用ListItem
函数,而不是在按下ListItem
时调用。{/ p>
我确信它一定是简单的,我省略了。有什么建议吗?
View1.js - 显示guests
的初始列表的视图:
import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
Text, List, ListItem } from 'native-base';
import { connect } from 'react-redux';
import { Actions as NavigationActions } from 'react-native-router-flux';
class View1 extends Component {
render() {
// This is the function that runs every time a ListItem component is rendered.
// Why is this not only running on onPress?
const goToView2 = (guest) => {
NavigationActions.view2(guest);
console.log('Navigation router run...');
};
return (
<Container>
<Header>
<Title>Header</Title>
</Header>
<Content>
<List
dataArray={this.props.guests}
renderRow={(guest) =>
<ListItem button onPress={goToView2(guest)}>
<Text>{guest.name}</Text>
<Text note>{guest.email}</Text>
</ListItem>
}
>
</List>
</Content>
<Footer>
<FooterTab>
<Button transparent>
<Icon name='ios-call' />
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
const mapStateToProps = state => {
console.log('mapStateToProps state', state);
return { guests: state.guests };
};
export default connect(mapStateToProps)(View1);
View2.js - 显示guest
中所选View1.js
的详细信息的视图:
import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
Text, List, ListItem } from 'native-base';
class View2 extends Component {
render() {
console.log('View2 props: ', this.props);
return (
<Container>
<Header>
<Title>Header</Title>
</Header>
<Content>
<Content>
<List>
<ListItem>
<Text>{this.props.name}</Text>
</ListItem>
</List>
</Content>
</Content>
<Footer>
<FooterTab>
<Button transparent>
<Icon name='ios-call' />
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
export default View2;
答案 0 :(得分:33)
尝试<ListItem button onPress={() => {goToView2(guest)}}
答案 1 :(得分:2)
const goToView2 = (guest) => {
NavigationActions.view2(guest);
console.log('Navigation router run...');
};
<ListItem button onPress={this.goToView2(guest)}>
如果你在函数中使用箭头函数那么它只是this.goToView2(来宾)...在渲染方法中写入箭头函数会导致性能问题......即使它可以忽略不计,最好避免它