我已经构建了一个自定义组件,它使用道具从屏幕接收数据,并使用带有数组的循环重复三次。每次重复组件时,我都可以通过将它们放在该屏幕中的数组中来发送不同的内容,例如文本和图像。我想是否有办法实现相同的东西,但这次给每个组件一个不同的“onPress”。我该如何设置?我需要弄乱数组吗?
组件.JS:
import React, { Component } from "react";
import styled from "styled-components";
const StudyComponent = props => {
return (
<Container>
<Cover>
<Image source={props.image} />
<Logo source={props.logo} />
<Title>{props.title}</Title>
</Cover>
</Container>
);
};
export default StudyComponent;
const Container = styled.View`
some css code!
`;
const Cover = styled.View`
some css code!
`;
const Image = styled.Image`
some css code!
`;
const Title = styled.Text`
some css code!
`;
const Logo = styled.Image`
some css code!
`;
屏幕.JS
import React, { Component } from "react";
import { TouchableOpacity} from "react-native";
import styled from "styled-components";
import THECOMPONENT from "../Components/THECOMPONENT";
class SelectedClasses extends Component {
static navigationOptions = { header: null };
render() {
const { navigation } = this.props;
const selected = navigation.getParam("selected");
return (
<Container>
<ComponentsContainer>
{components.map((component, index) => (
<TouchableOpacity
key={index}
onPress={() => {
this.props.navigation.push("Courses", {
selectedcomponent: component
});
}}
>
<StudyComponent
title={component.title}
image={component.image}
logo={component.logo}
/>
</TouchableOpacity>
))}
</ComponentsContainer>
</Container>
);
}
}
export default SelectedClasses;
const Container = styled.View`
some css code!
`;
const ComponentsContainer = styled.View`
some css code!
`;
//THE ARRAY WHERE I DYNAMICALLY ADD TITLES, IMAGES AND LOGOS TO EACH COMPONENT THAT GET REPEATED USING THE LOOP ABOVE!
const components = [
{
title: "STUDY",
image: require("../assets/STUDYCOMPONENT-THUMBNAIL.jpg"),
logo: require("../assets/STUDYCOMPONENT-ICON.png")
},
{
title: "GROUP CHAT",
image: require("../assets/GROUPCHATCOMPONENT-THUMBNAIL.jpg"),
logo: require("../assets/GROUPCHATCOMPONENT-ICON.png")
},
{
title: "FIND TUTOR",
image: require("../assets/FINDTUTORCOMPONENT-THUMBNAIL.jpg"),
logo: require("../assets/FINDTUTORCOMPONENT-ICON.png")
}
];
我尝试了不同的方法将 onPress 作为道具传递,但到目前为止还没有运气。很可能我做错了什么,因为我对 ReactNative 还比较陌生。
我希望能够让屏幕上的每个重复组件导航到不同的屏幕。ps 我正在使用 react-navigation 库