1、Props(属性)
自定义的组件也可以使用props。通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。下面是一个例子:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class Greeting extends Component {
render() {
return (
<Text>Hello {this.props.name}</Text>
);
}
}
export default class reactNativeBasis extends Component {
render() {
return (
<View style={styles.container}>
<Greeting name='huage' />
<Greeting name='fang' />
<Greeting name='feng' />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AppRegistry.registerComponent('reactNativeBasis', () => reactNativeBasis);
备注:props
是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变
2、state(状态)
我们使用两种数据来控制一个组件:props
和state
。props
是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state
。
一般来说,你需要在constructor
中初始化state
,然后在需要修改时调用setState
方法。
假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop。而文字的显示或隐藏的状态(快速的显隐切换就产生了闪烁的效果)则是随着时间变化的,因此这一状态应该写到state
中。
class Blink extends Component {
constructor(props) {
super(props)
this.state = {showText: true};
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState(previousState => {
return {showText: !previousState.showText}
});
},1000);
}
render() {
let display = this.state.showText ? this.props.text: ''
return (
<Text>{display}</Text>
);
}
}
export default class reactNativeBasis extends Component {
render() {
return (
<View style={styles.container}>
<Blink text='I love to blink' />
<Blink text='Yes blinking is so great' />
<Blink text='Why did they ever take this out of HTML' />
<Blink text='Look at me look at me look at me' />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AppRegistry.registerComponent('reactNativeBasis', () => reactNativeBasis);
When setState is called, reactNativeBasis will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.
3、Handling Text Input(处理文本输入)
TextInput
is a basic component that allows the user to enter text. It has an onChangeText
prop that takes a function to be called every time the text changed, and an onSubmitEditing
prop that takes a function to be called when the text is submitted.