defaultProps in React Native?

后端 未结 3 2155
终归单人心
终归单人心 2021-01-06 01:02

Is it possible to use defaultProps in React Native? I’ve tried the following 2 ways of defining defaultProps and I get null when trying to access the defaultProp

<         


        
相关标签:
3条回答
  • 2021-01-06 01:38

    I do it in ReactNative

    import React, {
        Component
    } from 'react';
    import {
        View,
        Text
    } from 'react-native';
    import PropTypes from 'prop-types';
    
    export default class foo extends Component {
        static propTypes = {
            name: PropTypes.array,
            prop2: PropTypes.string
        }
        static defaultProps = {
            array: [1, 2, 4],
            name: 'abc'
        }
        constructor(props) {
            super(props);
            this.state = {};
        }
        render() {
            return (
                <View>
                    <Text>Default Prop array is: {this.props.array}</Text>
                    <Text>Default Prop name is: {this.props.name}</Text>
                </View>
            );
        }
    }
    
    

    And then you can use these props like this.props.prop1 and this.props.prop2.

    0 讨论(0)
  • 2021-01-06 01:39

    You want this:

    Foo.propTypes = {
        someData: React.PropTypes.string
    };
    

    This says that someData should be a string, but it is not required.

    Then in your render(), you can do this:

    render() {
        return (
          <View> 
            {this.props.someData || Foo.defaultProps.someData} 
          </View>
        );
      }
    

    This will use this.props.someData if it's provided or Foo.defaultProps.someData if not.

    I also think you need to wrap {this.props.someData || Foo.defaultProps.someData} in a Text element (i.e., <Text>{this.props.someData || Foo.defaultProps.someData}</Text>).

    0 讨论(0)
  • 2021-01-06 01:52

    I always do it like this and it works just fine:

    class Foo extends React.Component {};
    
    Foo.propTypes = {
      animateBackground: PropTypes.bool
    };
    
    Foo.defaultProps = {
      animateBackground: false
    };
    
    export default Foo;
    
    0 讨论(0)
提交回复
热议问题