大多数初学react native 的人,对此深有困惑,故,再次分享一篇react native 的入门解惑篇
一: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的入门篇的详细内容。