我有这个自定义按钮组件:
import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { styles } from "./styles";
class TransactionFees extends Component {
test = () => {
const { speed, eth, usd,pressed,changeColor } = this.props;
console.log("speed, eth, usd,pressed,changeColor",speed, eth, usd,pressed,changeColor)
}
render() {
const { speed, eth, usd,pressed,changeColor,key } = this.props;
return (
<TouchableOpacity style={ pressed ? styles.pressedButton : null } onPress={changeColor}>
<Text style={styles.transactionFeeTitle}>{speed}</Text>
<Text style={styles.transactionFeeSubText}>{eth} ETH</Text>
<Text style={styles.transactionFeeSubText}>$ {usd} </Text>
</TouchableOpacity>
);
}
}
export default TransactionFees;
这就是我使用它的方式:
<TransactionFees pressed={pressed} changeColor={this.changeColor} key={"slow"} speed={"Slow"} eth={"0.000010"} usd={"0.02"} />
<TransactionFees pressed={pressed} changeColor={this.changeColor} key={"average"} speed={"Average"} eth={"0.000030"} usd={"0.03"} />
<TransactionFees pressed={pressed} changeColor={this.changeColor} key={"fast"} speed={"Fast"} eth={"0.000050"} usd={"0.04"} />
changeColor函数:
changeColor = () => {
const {pressed} = this.state
this.setState({pressed:!pressed})
}
当单击时,我只想让其中一个更改背景样式,但问题是当单击其中任何一个时,它们都会更改背景样式请提供如何解决此问题的解决方案?
您必须在父级中维护pressedKey,而不是像下面这样维护pressed。在这里,我们使用changeColor传递选定的键,并将其保留在父项中,该父项将用于比较和决定背景颜色。
class TransactionFeesContainer extends Component {
state = {
selectedKey: null,
};
changeColor = (key) => {
this.setState({ selectedKey: key });
};
render() {
return (
<View>
<TransactionFees
selectedKey={this.state.selectedKey}
changeColor={this.changeColor}
speedkey={'slow'}
speed={'Slow'}
eth={'0.000010'}
usd={'0.02'}
/>
<TransactionFees
selectedKey={this.state.selectedKey}
changeColor={this.changeColor}
speedkey={'average'}
speed={'Average'}
eth={'0.000030'}
usd={'0.03'}
/>
<TransactionFees
selectedKey={this.state.selectedKey}
changeColor={this.changeColor}
speedkey={'fast'}
speed={'Fast'}
eth={'0.000050'}
usd={'0.04'}
/>
</View>
);
}
}
class TransactionFees extends Component {
render() {
const { speed, eth, usd, speedkey, selectedKey } = this.props;
return (
<View>
<TouchableOpacity
style={speedkey === selectedKey ? styles.pressedButton : null}
onPress={() => {
this.props.changeColor(speedkey);
}}>
<Text style={styles.transactionFeeTitle}>{speed}</Text>
<Text style={styles.transactionFeeSubText}>{eth} ETH</Text>
<Text style={styles.transactionFeeSubText}>$ {usd} </Text>
</TouchableOpacity>
</View>
);
}
}