gpt4 book ai didi

javascript - React Native - 为什么要执行此函数?

转载 作者:可可西里 更新时间:2023-11-01 01:55:58 28 4
gpt4 key购买 nike

我刚刚开始全神贯注于 React Native,并使用 Redux 管理 stateNativeBase library对于我的 UI 组件和 react-native-router-flux正在处理 View 之间的导航。

目前我正在构建一个基本列表,该列表是根据 guest 对象数组创建的。该列表存储在 Redux 存储中,我可以访问它并进行相应显示。列表中的每个项目都与 guests 数组中的 guest 相关联。我想让列表中的每个项目都可触摸,然后将相关的 guest 对象作为属性传递给下一个 View 以显示详细信息。

为此,我使用了 onPress 函数,它是与 ListItem 组件关联的标准函数(参见 NativeBase 文档 here )。我也关注了the documentation对于 react-native-router-flux 并在组件本身之外定义了导航操作,以便 ListItem 在按下时调用它,而不是每次呈现时调用它。

我的问题是,我发现每次呈现 ListItem 时都会调用 onPress={goToView2(guest)} 函数,而不是专门在 ListItem 被按下。

我确信它一定是我遗漏的简单内容。有什么建议吗?

View1.js - 显示 guest 初始列表的 View :

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 - 显示来自 View1.js 的所选 guest 详细信息的 View :

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;

最佳答案

尝试做<ListItem button onPress={() => {goToView2(guest)}}

关于javascript - React Native <ListItem onPress={...}> - 为什么要执行此函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275154/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com