我正在使用react native开发一个项目。我使用了地图功能来渲染按钮。当页面加载时,第一个按钮要为蓝色,其余按钮要为白色。单击下一个按钮后,想要更改上一个按钮的颜色和图像。按下的按钮要为蓝色。截至目前,当我单击第一个按钮时,其余按钮的颜色也在改变。任何人都可以纠正我哪里出了问题。预先感谢。
constructor(props) {
super(props);
this.state = {
isLoading: false,
prd: [],
on: false,
prdData: "All",
};
}
componentDidMount() {
this.setState({ isLoading: false });
let data = [
{
id: 0,
value: "All",
img1: require("../../../kr/images/all_white.png"),
img2: require("../../../kr/images/all_blue.png"),
},
{
id: 41,
value: "list",
img1: require("../../../kr/images/package_white.png"),
img2: require("../../../kr/images/package_blue.png"),
},
{
id: 13,
value: "list2",
img1: require("../../../kr/images/accident_white.png"),
img2: require("../../../kr/images/accident_blue.png"),
},
{ id: 14, value: "Term" },
];
this.setState({ prd: data });
}
render() {
const { on } = this.state;
return (
<View>
{/* Button contain starts */}
<View style={styles.container}>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
>
{this.state.product.map((item, i) => {
return (
<Button
onPress={() => {
this.setState({ on: !this.state.on });
}}
style={on ? styles.btnActive : styles.btnNonActive}
>
<Image
style={{
width: 18,
height: 17,
flex: 1,
flexDirection: "row",
backgroundColor: "white",
}}
source={
this.state.activeIndex === 0 ? item.img1 : item.img2
}
/>{" "}
<Text
style={{
color: "black",
fontSize: 11,
flex: 1,
flexDirection: "row",
}}
>
{item.value}
</Text>
</Button>
);
})}
</ScrollView>
</View>
)
答案 0 :(得分:0)
创建一个项目组件并以int处理颜色更改状态,不要使用主要组件,
小吃:https://snack.expo.io/@ashwith00/grounded-cookie
这里是一个例子,
const data = ['apple', 'ball', 'cat', 'dog'];
export default function App() {
return (
<View style={styles.container}>
<ScrollView>
{data.map((item) => (
<Item
key={item}
item={item}
onPress={() => {
console.log(item);
}}
/>
))}
</ScrollView>
</View>
);
}
const Item = ({ item, onPress }) => {
const [on, setOn] = React.useState(false);
return (
<View style={styles.item}>
<Text>{item}</Text>
<TouchableHighlight
onPress={() => {
setOn(true);
onPress();
}}
style={[styles.button, on && styles.activeBuyton]}>
<Text style={{ color: '#ffffff' }}>Click</Text>
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
item: {
alignSelf: 'stretch',
height: 100,
marginBottom: 20,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#00000010',
},
button: {
alignSelf: 'stretch',
marginHorizontal: 10,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'blue',
},
activeBuyton: {
backgroundColor: 'green',
},
});