[英]How do I handle press and unpress touchable component with style changes?
The idea is to create a specific Touchable component acting like a button and have a feeling of pressed and unpressed, and using this component many times on my app but only one can be pressed at a time.我的想法是创建一个像按钮一样的特定 Touchable 组件,并具有按下和未按下的感觉,并在我的应用程序上多次使用该组件,但一次只能按下一个。 If one is touched and then another one is touched, the first one should be unpressed and the second one should be pressed.
如果先触摸一个然后再触摸另一个,则应先松开第一个,然后按第二个。 The idea is not to use Redux to solve this problem.
思路不是用Redux来解决这个问题。
I'm already handling which component was pressed, and sending through props the actions to the component.我已经在处理按下哪个组件,并通过道具将操作发送到组件。 But i don't know how to manage all buttons at the same time in a generic way, by that I mean, not creating a variable to each button.
但我不知道如何以通用方式同时管理所有按钮,我的意思是,不是为每个按钮创建一个变量。
my App:我的应用程序:
<View>
<ActivityButton activityTitle={"B1"} submit={() => this.submitHandler("B1")} />
<ActivityButton activityTitle={"B2"} submit={() => this.submitHandler("B2")} />
</View>
my Component (ActivityButton):我的组件(活动按钮):
this.state={active:false}
<TouchableOpacity style={this.state.active ? styles.buttonPress : styles.button} onPress={this.props.submit}>
<View>
<Text>{this.props.activityTitle}</Text>
</View>
</TouchableOpacity>
I assume what you trying to do something like a Radio button groups?我假设您正在尝试做类似单选按钮组的事情? If your buttons only located in single page, you can achieve by using state in
MyApp
to check which buttons is enabled instead of button itself.如果您的按钮仅位于单个页面中,您可以通过使用
MyApp
中的状态来检查启用了哪些按钮而不是按钮本身来实现。
MyApp我的应用程序
constructor(props) {
super(props);
this.state = {
buttonIdThatEnable: "",
};
}
submitHandler = (buttonId) => {
this.setState({
buttonIdThatEnable: buttonId,
});
}
render() {
return (
<View>
<ActivityButton
activityTitle={"B1"}
active={this.state.buttonIdThatEnable === "B1"}
submit={() => this.submitHandler("B1")}
/>
<ActivityButton
activityTitle={"B2"}
active={this.state.buttonIdThatEnable === "B2"}
submit={() => this.submitHandler("B2")}
/>
</View>
)
}
ActivityButton (Use props.active to determine style) ActivityButton(使用props.active确定样式)
<TouchableOpacity style={this.props.active ? styles.buttonPress : styles.button}
onPress={this.props.submit}>
<View>
<Text>{this.props.activityTitle}</Text>
</View>
</TouchableOpacity>
If your Buttons are located in different components and you do not want to use Redux, you may consider the React Context API如果你的 Buttons 位于不同的组件中并且你不想使用 Redux,你可以考虑React Context API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.