简体   繁体   中英

How do I type a function inside the stylesheet in React Native CLI?

import { StyleSheet, TextStyle, ViewStyle, ImageStyle } from 'react-native';

export const styles = StyleSheet.create({
    spacing: (marginBottom: number) => {
        return {
            marginBottom,
        }
    }
});

The error returned was:

Type '(marginBottom: number) => { marginBottom: number; }' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.ts(2322)

The code even works, but returns the mentioned error. Usage is supposed to be like this:

<View style={styles.spacing(50)}>
    <Button title={'Login'} onPress={handleSign} />
</View>

I think that's not allowed to pass to functions/class to StyleSheet.create.

You can apply static style and inline style like this:

<View style={[styles.myStaticStyle, { marginBottom:50 }]}>
    <Button title={'Login'} onPress={handleSign} />
</View>

You can apply style.prop conditionally like this:

<View style={[i > 20 ? { marginBottom:50 } : null]}>
    <Button title={'Login'} onPress={handleSign} />
</View>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM