reactjs - React Native:根据是否处于活动状态更改组件属性的布尔值
问题描述
我有一个 React Native 组件,它由 3 个按钮组件组成,每个组件都有一个名为inner
. 如果inner={true}
然后按钮显示为按下,而如果inner={false}
然后按钮显示为浮雕。
任何时候都只能有一个按钮处于活动状态,我想让它显示活动按钮inner={true}
,而其他两个非活动按钮将显示inner={false}
。
下面是我的代码:
const ChoiceContainer = props => {
const {children} = props;
return <View>{children}</View>;
};
const SendTransaction = () => (
<ChoiceContainer>
<Text>Component 1</Text>
</ChoiceContainer>
);
const Remove = () => (
<ChoiceContainer>
<Text>Component 2</Text>
</ChoiceContainer>
);
const History = () => (
<ChoiceContainer>
<Text>Component 3</Text>
</ChoiceContainer>
);
export default class MyComponent extends Component {
state = {
sceneType: 'add',
};
showSend = () => {
this.setState({sceneType: 'add'});
};
showReceive = () => {
this.setState({sceneType: 'remove'});
};
showHistory = () => {
this.setState({sceneType: 'history'});
};
renderScene = type => {
if (type === 'add') {
return <SendTransaction />;
}
if (type === 'remove') {
return <ReceiveTransaction />;
}
if (type === 'history') {
return <TransactionHistory />;
}
};
render() {
const {sceneType} = this.state;
return (
<View>
<View>
<TouchableOpacity onPress={this.showAdd}>
<Button inner={true}>Button 1</Button>
<TouchableOpacity onPress={this.showRemove}>
<Button inner={false}>Button 2</Button>
</TouchableOpacity>
<TouchableOpacity onPress={this.showHistory}>
<Button inner={false}>Button 3</Button>
</TouchableOpacity>
</View>
<View>{this.renderScene(sceneType)}</View>
</View>
);
}
}
解决方案
<TouchableOpacity onPress={this.showAdd}>
<Button inner={sceneType === 'add' }>Button 1</Button>
<TouchableOpacity onPress={this.showRemove}>
<Button inner={sceneType === 'remove'}>Button 2</Button>
</TouchableOpacity>
<TouchableOpacity onPress={this.showHistory}>
<Button inner={sceneType=== 'history'}>Button 3</Button>
</TouchableOpacity>