如何更改外部的样式表属性?React Native



我举了这个例子:

import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default function App() {
const handlePress = e => {
styles.button.borderColor = '#FF0000';
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={handlePress}>
<Text style={styles.text}>Example</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
button: {
borderWidth: 10,
borderColor: '#000000',
borderRadius: 15,
backgroundColor: '#8a2be2',
width: 125,
height: 125,
justifyContent: 'center',
alignItems: 'center'
},
text: {
color: '#fff',
fontSize: 25
}
});

我试图更改按钮borderColor的值,调用一个函数来执行此操作,但出现了一个错误:"试图分配给只读属性">

您需要为此更改state,您可以使用useState,导入它,然后在按下时更改状态:

import React, {useState} from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default function App() {
const [buttonClicked, setButtonClicked] = useState(false)
const handlePress = e => {
setButtonClicked(true)
};
return (
<View style={styles.container}>
<TouchableOpacity style={buttonClicked?[styles.button, {borderColor: 'red'}]:styles.button} onPress={handlePress}>
<Text style={styles.text}>Example</Text>
</TouchableOpacity>
</View>
);
}

启动onPress事件时,您似乎正在尝试编辑样式对象。相反,您需要编辑事件处理程序传递的事件对象的样式,在本例中,它将是元素。样式对象用于在加载构件时应用样式,但在此之后,您需要编辑图元本身的实例。

在handlePress函数中,如果是console.log(e.target),则应在按下事件触发后看到打印到控制台的元素。您将能够看到与它相关联的所有属性,其中一个属性就是样式。这就是您想要更改的样式属性。像这样:

let obj = e.target;
obj.style.borderColor = '#FF0000';

查看事件处理程序发生了什么的一个好方法是只需console.log您从事件中获得的对象。你会明白你得到的是正确的还是不正确的对象,并开始看到你可以用它做的所有事情。事件是一个有很多选择的大世界。有疑问时,console.log!

最新更新