在React Native中使用样式化组件捕获Pressable Press

kdfy810k  于 2023-04-22  发布在  React
关注(0)|答案(2)|浏览(120)

有没有办法将pressed属性传递给styled-components?
我现在拥有的:

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledPressable = styled(Pressable)``;

const App = () => {
  return (
    <View>
      <StyledPressable
        onPress={() => null}
        android_ripple={{ color: 'black', borderless: true }}>
        <Text>Log in</Text>
      </StyledPressable>
    </View>
  );
};

export default App;

我想达到的目标

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledPressable = styled(Pressable)`
  background-color: ${props => pressed ? 'black' : 'blue'}    // change color on press, eg.
`;

const App = () => {
  return (
    <View>
      <StyledPressable
        onPress={() => null}
        android_ripple={{ color: 'black', borderless: true }}>
        pressed={pressed}    // this property "pressed" does not exist.
        <Text>Log in</Text>
      </StyledPressable>
    </View>
  );
};

export default App;

This is the official docs。它使用内联样式,我不能使用样式化的组件。

izj3ouym

izj3ouym1#

我不认为目前有一种方法。一种解决方案是在PressableText之间使用View,并在其中完成所有样式:

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledView = styled.View`
   background-color: ${({pressed}) => pressed ? 'black' : 'blue'}    
`;

const App = () => {
    return (
        <View>
           <Pressable onPress={() => null}>
             {({pressed}) => (
               <StyledView pressed={pressed}>
                 <Text>Log in</Text>
               </StyledView>
             )}
           </Pressable>
        </View>
    );
};

export default App;
atmip9wb

atmip9wb2#

是的,有一种方法可以使用'pressed',使用一个返回数组的函数。

<View style={styles.buttonView}>
    <Pressable
        onPress={() => doSomething()}
        style={({ pressed }) => {
            return [
                pressed
                    ? globalStyles.buttonSelected
                    : globalStyles.buttonUnselected,
            ];                                                                  
        }}> 
        <Text style={globalStyles.buttonUnselectedText}>
            Terminate session
        </Text>
    </Pressable>
</View>

相关问题