我刚刚开始学习React Native(从Android背景(。我想更改视图的背景颜色。我需要在不使用状态/道具的情况下执行此操作,因为我不想再次渲染它。
我已经引用了视图并能够使用另一个按钮的 onPress(( 访问它
如何更改视图的背景?
设置 ref:
ref={component => this.myref = component}
并使用 setNativeProps 设置背景
this.myref.setNativeProps({
style:{backgroundColor: '#3fba29'}
});
希望这对某人有所帮助:)
在使用它之前,请尝试使用 setState 解决您的问题。
https://reactnative.dev/docs/direct-manipulation
在单一值中,它非常容易
ChangeBackground(){
this.setState({
backgroundColor:'blue'
)}
}
render() {
return (
<View onPress={()=>this.ChangeBackground()}style={{backgroundColor:'red'}}>
....
</View>
在数组数据中,您必须使用索引值。借助索引或 id 更新背景颜色
像这样的东西,
const original = this.state.array;
const single_array = this.state.array.find(
x => x.id === id,
);
single_array.backgroundColor = 'blue';
original[index] = single_array;
this.setState({
array: original,
});