React Native之Props(属性)和State(状态)和简单样式简单使用
1 Props(属性)和State(状态)和简单样式简单使用App.js代码如下
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, NativeModules, DeviceEventEmitter, Image} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
var myAndroidToast = NativeModules.MyToast;
type Props = {};
class Greet extends Component {
render() {
return (<Text>Hello {this.props.name}</Text>);
}
}
class Blink extends Component {
constructor(props){
super(props);
this.state = {isShowing: true};
setInterval(() => {
this.setState(previousState => {
return {isShowing: !previousState.isShowing};
});
},1000);
}
render() {
let display = this.state.isShowing? this.props.text : 'chenyu';
return(
<Text>{display}</Text>
);
}
}
export default class App extends Component<Props> {
componentWillMount(){
//监听事件名为EventName的事件
DeviceEventEmitter.addListener('EventName', function() {
alert("Android send js msg ");
});
}
constructor(props){
super(props);
this.state={
myName:'chenzixuan',
num:0,
isShowingText:true
}
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState(previousState => {
return {num: ++this.state.num};
});
}, 1000);
}
render() {
let pic = {uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'};
return (
<View style={styles.container}>
<Text onPress={()=> this._androidShowMsg()} style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.red}>To get started, edit App.js</Text>
<Text style={styles.bigblue}>{instructions}</Text>
<Text style={styles.instructions}>{this.state.myName}</Text>
<Text style={styles.instructions}>{this.state.num}</Text>
<Greet name = 'chenyu'></Greet>
<Blink text = 'chenzixuan'></Blink>
</View>
);
}
_androidShowMsg = () => {
var value = myAndroidToast.showMyName();
this.setState({myName:value});
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
bigblue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 39
},
red: {
color: 'red'
},
});
2 运行结果如下
赞 (0)