React Native填坑之旅--Stateless組件

Stateless component也叫無狀態組件。有三種方法能夠建立無狀態組件。less

通常一個組件是怎麼定義的:flex

好久之前的方法:

const Heading = createClass({
    render() {
        return <Text>{this.props.title}</Text>
    } 
})

後來有了ES6

class Heading extends Component { 
    render() {
        return <Text>{this.props.title}</Text> 
    } 
}

接ES6的光,看起來好了不少。ui

填坑

可是,一個組件不須要狀態的時候還給出那麼多的定義仍是不夠精煉,太麻煩。因而用stateless component來填這個坑。this

// Stateless functions
const Heading = ({title}) => <Text>{title}</Text>

看起來是多麼的簡潔、有力!spa

來個完整的例子:

const HiTitle = ({title}) => (
  <Text style={styles.title}>
    {title}
  </Text>
)

const App = () => (
  <View style={styles.container}>
    <HiTitle title='A stateless component' />
  </View>
)

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    title: {
        fontSize: 36,
        fontWeight: 'bold',
        color: 'red'
    }
})

AppRegistry.registerComponent('AwesomeProject', () => App);

運行起來是這樣的:code

顯然stateless component更加的有表達力。可是在一個APP裏也不可能全部的組件都是無狀態的。因此最好是讓一些容器(container)來包裹各類組件,而這些組件就能夠寫成是無狀態的。用過Redux的都知道這麼搞頗有前途。component

無狀態組件沒有生命週期的方法和顯示的狀態,這樣加大的減小了代碼量。可是無狀態組件仍是能夠接收props的。好比,上例中的const HiTitle = ({title}) => (...)裏的{ title }就是用來解析賦值props的。生命週期

既然能夠接收props,那麼也就能夠設置propTypesdefaultProps。如:rem

const HiTitle = ({title}) => (
  <Text style={styles.title}>
    {title}
  </Text>
)

HiTitle.propTypes = {React.PropTypes.string.isRequired}
HiTitle.defaultProps = {title: 'stateless component'}
相關文章
相關標籤/搜索