更改 Press 事件 React Native 的样式

问题描述 投票:0回答:4

我在使用 onPress 事件更改样式时遇到问题,最初我的宽度 = 75 和高度(default values of width and height),但是当我使用 onPress 时我想触发该方法(method What I would like to use for replace styles value),该方法将替换宽度高度65。你能告诉我解决这个问题的方法吗?

react-native styles
4个回答
2
投票

您可以使用从“react-native”导入的 touchableHighlight 您的构造函数应该保存一个用于表示新闻状态的变量:

constructor(props) {
  super(props);
  this.state = {
    pressStatus: false 
  };
}

按下 touchableHighlight 时处理的两个函数。

_onHideUnderlay(){
  this.setState({ pressStatus: false });
}
_onShowUnderlay(){
  this.setState({ pressStatus: true });
}

可触摸的可能看起来像

<TouchableHighlight
        onPress={()=>{}}
        activeOpacity={0.5}
        style={this.state.pressStatus ? styles.buttonPress : styles.button}
        onHideUnderlay={this._onHideUnderlay.bind(this)}
        onShowUnderlay={this._onShowUnderlay.bind(this)}
        >
  <Text>Press</Text>
</TouchableHighlight>

然后添加到样式表中

button: {
    alignSelf:'center',
    borderColor: '#000066',
    backgroundColor: '#000066',
    width:65,
    height:65
  },
  buttonPress: {
    alignSelf:'center',
    borderColor: '#000066',
    backgroundColor: '#000066',
    width:75,
    height:75
  },

2
投票

您可以在

75
方法中将状态变量从
65
更改为
onPress
,并使用该变量覆盖您的宽度/高度。

<YourElement style={[styles.yourOriginalStylesheet, {width: this.state.size, height: this.state.size}]}>

或者,您可以定义另一个样式对象,并根据您在

onPress
中更改的布尔状态变量有条件地应用它。

<YourElement style={[styles.yourOriginalStylesheet, this.state.changeSize && styles.yourStylesheetWithNewSizes]}>


0
投票

我在我的手机上,所以这变成了一种我无法验证的伪代码。

解决这个问题的一种方法是创建一个名为 onPress 的函数。该函数改变状态变量。 在样式中,您可以查看状态变量是否为 true 或 false。

功能 handlePress(){this.setState({pressed:true})}

在您的按钮/视图或您想要的样式中 onPress={()=>handlePress()}

在你的造型中

宽度:this.state.pressed?75:65

如果按下为真,它将显示问号后的第一个值,否则显示第二个值。


0
投票

更好地使用 Pressable,它会在

style
属性中返回一个名为
pressed
的参数。

不再需要

useState
,让您可以制作轻量级组件。

© www.soinside.com 2019 - 2024. All rights reserved.