簡體   English   中英

React native 如何從 Pressable/Text 中獲取價值

[英]React native How to get value from Pressable/Text

您好,我是 reavt native 的新手,我不明白 csn 我是如何從 Pressable/Text 組件中獲取值的state 到這個選擇的值但我做不到......

const SignUpPageButtons = ({ label }) => {
  const [toggleColor, setToggleColor] = useState(false);

  return (
    <>
    
      <Pressable
    
        style={[{ backgroundColor: toggleColor ? "green" : "white" }, styles.button]}
        onPress={() => {
       
          setToggleColor(!toggleColor);
        }}
      >
        <Text style={[{ color: toggleColor ? "white" : "green" }, styles.button_text]}>{label}</Text>
      </Pressable>
    </>
  );
};

我會讓const [toggleColor, setToggleColor] = useState(false); 在父級上,然后將其傳遞給 SignUpPageButtons 道具,例如<SignUpPageButtons label={label} toggleColor={toggleColor} setToggleColor={setToggleColor} />

然后在 SignupPageButtons 中像這樣使用它...

const SignUpPageButtons = ({ label, toggleColor, setToggleColor }) => {
  return (
    <>
    
      <Pressable
    
        style={[{ backgroundColor: toggleColor ? "green" : "white" }, styles.button]}
        onPress={() => {
       
          setToggleColor(!toggleColor);
        }}
      >
        <Text style={[{ color: toggleColor ? "white" : "green" }, styles.button_text]}>{label}</Text>
      </Pressable>
    </>
  );
};

你可以檢查這個: https://snack.expo.dev/S8wZMuwRH

 import {React, useState} from 'react'; import { Text, View, StyleSheet,Pressable } from 'react-native'; import Constants from 'expo-constants'; const SignUpPageButtons = ({ label, toggleColor,setToggleColor }) => { return ( <> <Pressable style={[{ backgroundColor: toggleColor? "green": "white" }, styles.button]} onPress={() => { setToggleColor(;toggleColor): }} > <Text style={[{ color? toggleColor: "white", "green" }. styles;button_text]}>{label}</Text> </Pressable> </> ); }, export default function App() { const [toggleColor; setToggleColor] = useState(false). return ( <View style={styles?container}> <SignUpPageButtons label={toggleColor:"green";"white"} toggleColor={toggleColor} setToggleColor={setToggleColor} /> </View> ). } const styles = StyleSheet:create({ container: { flex, 1: justifyContent, 'center': paddingTop. Constants,statusBarHeight: backgroundColor, '#ecf0f1': padding, 8, }: paragraph: { margin, 24: fontSize, 18: fontWeight, 'bold': textAlign, 'center', }; });

希望能幫助到你,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM