首页 / REACT / ReactNative的入门篇
ReactNative的入门篇
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了ReactNative的入门篇,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2683字,纯文字阅读大概需要4分钟。
内容图文
![ReactNative的入门篇](/upload/InfoBanner/zyjiaocheng/302/56f82072c6414b308267bc2813899d5a.jpg)
一:Props(属性)
大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props(属性)。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变
通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。下面是一个例子:
import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; class Greeting extends Component { render() { return ( <Text>Hello {this.props.name}!</Text> ); } } class LotsOfGreetings extends Component { render() { return ( <View style={{alignItems: 'center'}}> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> </View> ); } } AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);
二:State(状态)
我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。
一般来说,你需要在constructor中初始化state(译注:这是ES6的写法,早期的很多ES5的例子使用的是getInitialState方法来初始化state,这一做法会逐渐被淘汰),然后在需要修改时调用setState方法。
假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop。而文字的显示或隐藏的状态(快速的显隐切换就产生了闪烁的效果)则是随着时间变化的,因此这一状态应该写到state中。
import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; class Blink extends Component { constructor(props) { super(props); this.state = { showText: true }; // 每1000毫秒对showText状态做一次取反操作 setInterval(() => { this.setState({ showText: !this.state.showText }); }, 1000); } render() { // 根据当前showText的值决定是否显示text内容 let display = this.state.showText ? this.props.text : ' '; return ( <Text>{display}</Text> ); } } class BlinkApp extends Component { render() { return ( <View> <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> ); } } AppRegistry.registerComponent('BlinkApp', () => BlinkApp);
实例2:
import React, { Component } from 'react'; import { AppRegistry, Text, TextInput, View } from 'react-native'; class PizzaTranslator extends Component { constructor(props) { super(props); this.state = {text: ''}; } render() { return ( <View style={{padding: 10}}> <TextInput style={{height: 40}} placeholder="Type here to translate!" onChangeText={(text) => this.setState({text})} /> <Text style={{padding: 10, fontSize: 42}}> {this.state.text.split(' ').map((word) => word && '
以上就是React Native的入门篇的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的ReactNative的入门篇全部内容,希望文章能够帮你解决ReactNative的入门篇所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。