Sha*_*ika 4 react-native touchableopacity
我的 RN 应用程序中有以下代码。
<TouchableOpacity
// onPress={onPress}
onPressIn={this.handlePressIn}
onPressOut={this.handlePressOut}
disabled={disabled}
style={[
styles.button,
buttonStyle,
this.buttonStyles(),
]}
>
<Text>Hello</Text>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
我想在按下 TouchableOpacity 时更改其颜色。因此,在 onPressIn 中,我将颜色更改为 darkRed,但它显示浅红色或类似的颜色。那里不能设置深色。这里有什么问题呢?如何更改颜色直到 onPressOut?颜色应该是深色的。
找到了解决方案。在 TouchableOpacity 中设置 activeOpacity={1}。
<TouchableOpacity
onPress={onPress}
activeOpacity={1}
/>
Run Code Online (Sandbox Code Playgroud)
编辑:
我想我有点过度设计了。您可以简单地使用该activeOpacity={1}道具。
问题:
问题在于,它TouchableOpacity已经通过降低按钮的不透明度来提供反馈,允许用户按下按钮时可以看到背景。因此,即使您更改按钮的背景颜色,您也不会注意到它。幸运的是,我有一个解决方案给你。
解决方案:
您可以TouchableWithoutFeedback与其他视图一起使用来创建您想要的行为。
代码:
<TouchableWithoutFeedback
onPressIn={() => this.setState({pressIn: true })}
onPressOut={() => this.setState({pressIn: false})}
>
<View
// change the color depending on state
style={{ backgroundColor: this.state.pressIn ? '#4c7d4c': '#98FB98'}}
>
<Text> Custom Button </Text>
</View>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)
输出:
工作示例:
https://snack.expo.io/@tim1717/quiet-watermelon
| 归档时间: |
|
| 查看次数: |
7351 次 |
| 最近记录: |