【问题标题】:Catch Pressable press with styled-components in React Native在 React Native 中使用样式化组件捕获 Pressable press
【发布时间】:2021-01-29 10:53:40
【问题描述】:

有没有办法将pressed 属性传递给样式组件?

我现在拥有的:

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。它使用内联样式,我无法使用样式组件。

【问题讨论】:

    标签: javascript reactjs react-native styled-components


    【解决方案1】:

    我认为目前没有办法。一种解决方法是在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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 2018-02-09
      • 2017-07-16
      • 2020-09-26
      • 2020-05-03
      • 2021-09-18
      • 2021-09-23
      • 2021-11-25
      相关资源
      最近更新 更多