本人始终认为最好最权威的学习资料就应该是官方文档
Props(属性)
大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为Props
,这些参数一经制定我们就不在去改变它们。
下面我们就以基础组件Image
为例,在创建Image
组件时我们会传入source
属性来指定图片地址,传入style
属性来控制其尺寸和位置。
export default class ReactNativePropsAndStatus extends Component {
render() {
return (
<View>
<Image
source={{uri: 'https://github.com/fluidicon.png'}}
style={styles.imgUrl}
/>
<Image
source={require('./ImageSource.GithubIcon.png')}
style={styles.ImagePath}
/>
</View>
);
}
}
const styles = StyleSheet.create({
imgUrl: {
top: 50,
left: 50,
width: 256,
height: 256
},
ImagePath: {
top: 50,
left: 50,
width: 256,
height: 256
}
})

当然
Image
的属性还有很多这里只是为了说明属性这个名词,更多的属性可以参考官方文档
State(状态)
上面也提到我们用两组数据来控制一个组件:Props
和State
,其中Props
是在父组件中指定,并且在指定组件的生命周期内不再改变,对于需要改变的数据,我们使用State
在ES6
的规范中需要在constructor
中初始化State
,然后在需要修改的地方调用setState
方法。
下面我们列举一个例子:假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop
。而文字的显示或隐藏的状态则是随着时间变化的,因此这一状态应该写到state
中
export default class ReactNativePropsAndStatus extends Component {
render() {
return (
<View>
<BlinkTextTest displayText='Please look at me' />
</View>
);
}
}
class BlinkTextTest extends Component {
constructor(props) {
super(props)
this.state = {
showText: true
}
setInterval(() => {
this.setState({
showText: !this.state.showText
})
}, 1000)
}
render() {
let displayText = this.state.showText ? this.props.displayText : ' '
return (
<Text style={styles.blinkText}>
{displayText}
</Text>
)
}
}
const styles = StyleSheet.create({
blinkText: {
top: 60,
left: 0,
right: 0,
height: 30,
textAlign: 'center'
}
})
在实际的项目中我们一般不会在定时器函数中来操作state
。一般我们会接受到服务器返回的新数据或在用户输入数据之后对state
操作。当然你也可以使用一些状态容器如Redux
来同意管理数据流。
欢迎讨论
Email:huliuworld@yahoo.com
Github: https://github.com/LHCoder2016/ReactNativeNote.git
网友评论