創(chuàng)建 MyComponent.js :
- ES6 方式創(chuàng)建:
export default 的作用是導(dǎo)出該類,以供外面使用。
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
export default class MyComponent extends Component {
render() {
return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello {this.props.name}</Text>
}
}
- ES5 方式創(chuàng)建:(測(cè)試不通過。。。但是學(xué)習(xí)視頻通過,估計(jì)已經(jīng)不可用。)
module.exports 的作用是導(dǎo)出該類,以供外面使用。
var MyComponent=React.createClass({
render(){
return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello </Text>
}
})
module.exports = MyComponent;
- 函數(shù)式(無狀態(tài),不能使用this)
module.exports 的作用是導(dǎo)出該類,以供外面使用。
function MyComponent(props) {
return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello {props.name}</Text>
}
module.exports = MyComponent;
無參數(shù)的寫法:
function MyComponent() {
return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello</Text>
}
module.exports = MyComponent;
App.js 代碼:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
import MyComponent from './MyComponent.js';
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<MyComponent name="yococo"/>//使用指定的Componet
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5fcff',
marginTop: 80,
}
});