【问题标题】:in react native how i can change background color for every view element independent在本机反应中,我如何独立更改每个视图元素的背景颜色
【发布时间】:2021-08-29 13:16:05
【问题描述】:

对于每个独立的视图元素,当我按下它们而不影响其他视图并保存按下状态时,下次我可以找到仍然按下的内容,并且当按下它们时我可以更改其他视图的颜色而不会丢失预览视图的状态

问题是当我从两个任务中按一个时,另一个任务也改变了她的背景颜色

import React, { useState } from 'react';
import { 
   SafeAreaView, 
   View,
   FlatList, 
   StyleSheet, 
   Text,
   TouchableOpacity, 
} from 'react-native';

 
function App() {

  const [changBack,backgroundColor]=useState('green')

  function changIt() {
    backgroundColor('red');
  }
  
  const DATA1 = 'Task one';
  const DATA2 = 'Task two';

  return (
    <View>

      <TouchableOpacity
       style={{
        flex: 1,
        backgroundColor:changBack,
        padding: 20,
       }}  
       onPress={changIt}>
        <View>
          <Text>{DATA1}</Text>
        </View>
      </TouchableOpacity>

      <TouchableOpacity
       style={{
        flex: 1,
        backgroundColor:changBack,
        padding: 20,
       }}  
       onPress={changIt}>
        <View>
          <Text>{DATA2}</Text>
        </View>
      </TouchableOpacity>
   
    </View>

  );
  
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection:'column',
    textAlign:'right',
    justifyContent:'space-evenly',
  },
});

export default App;

【问题讨论】:

    标签: react-native styles react-native-android


    【解决方案1】:

    兄弟,我注意到你在Style 上通过backgroundColor&lt;TouchableOpacity&gt;,所以它肯定行不通。 backgroundColor 仅适用于 &lt;View&gt;,但不适用于 TouchableOpcacity。

    做这样的事~

     <View>
        <View style={{backgroundColor:changBack}}>
            <TouchableOpacity onPress={changeIt}>
                <View>
                    <Text>Heyya</Text>
                </View>
            </ToucableOpacity>
        </View>
    </View>
    

    或者这个,

        <View> 
         <TouchableOpacity onPress={changeIt}>
            <View style={{backgroundColor:changBack}}>
                <Text>Heyya</Text>
            </View>
        </ToucableOpacity>
       </View>
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2018-04-14
      • 1970-01-01
      相关资源
      最近更新 更多