【问题标题】:How to dynamically change zIndex in react native?如何在本机反应中动态更改zIndex?
【发布时间】:2021-11-22 00:45:02
【问题描述】:

我是 react native 的新手,如何在 react native 中动态更改 Zindex?或者如何使用其他动态方式隐藏/显示?

import { styles } from './App_styles';

 export default function App() {

  return (
    <View style={styles.body}>
      
      <Pressable onPress={()=>{styles.popup.zIndex=0}}>
      <View style={styles.popup}>
        
      </View>
      </Pressable>

      <View style={styles.main_content}>

      </View>

    </View>
  );
  }

App_styles:

export const styles = StyleSheet.create({

    body:{
        backgroundColor: 'gray',
        height:'100%',
    },

    popup: {
        position:'absolute',
        backgroundColor: 'rgba(0,0,0, 0.5)',
        height:'100%',
        width:'100%',
        zIndex:1,
        alignSelf:'center',
        marginTop:'30%',
    },
    
    main_content:{
        backgroundColor: 'red',
        width:'100%',
        height:'100%'

    },
    
});

我不确定如何使用 js 在 react native 中动态更改属性

【问题讨论】:

标签: javascript react-native


【解决方案1】:

你可以使用 state 来更新弹窗的样式:

import { styles } from './App_styles';
import {useState} from 'React';

 export default function App() {

  const [zIndex, setZIndex] = useState(1);

  return (
    <View style={styles.body}>
      
      <Pressable onPress={()=>{setZIndex(0)}}>
      <View style={[styles.popup, {zIndex: zIndex}]}>
        
      </View>
      </Pressable>

      <View style={styles.main_content}>

      </View>

    </View>
  );
  }

【讨论】:

  • 只需将它们链接到文档页面即可,无需在此处发布答案。
  • @ChrisG 我认为这个答案很好,而且答案与 stylesheet.create 不一样在 react 中不存在所以很多人可能没有意识到你可以在数组中内联样式
  • @ChrisG 这肯定是个初学者问题
  • 非常感谢,但我有点困惑为什么我们不能直接更改样式的属性?就像在我的代码中我做了styles.popup.zIndex=0 我的意思是如果你不能直接改变css中的值,那么javascript的用途是什么
  • @cakelover 在 React 中,如果你想要任何 UI 更新,你必须更新状态以使其再次呈现,首先检查 React 的基础知识
【解决方案2】:

只需使用 useState 钩子

  import { styles } from './App_styles';

  export default function App() {
  const [show, setShow] = useState(true)

  return (
   <View style={styles.body}>
   {show && <View style={styles.popup}>
    
  </View>}
  
  <TouchableOpacity onPress={()=>setShow(!show)}>
  <Text>Show/Hide</Text>
  </TouchableOpacity>

  <View style={styles.main_content}>

  </View>

</View>
  );
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2016-12-24
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多