转载:http://blog.csdn.net/pz789as/article/details/52537028
我们在项目里面,经常会用的批次渲染,比如一个列表渲染很多个item,或者一个横排或者竖排同时渲染多个数据。
例如:
- render1(){
- vararr=[];
- for(vari=0;i<5;i++){
- arr.push(
- Textstyle={{fontSize:20,color:'red'}}>
- 这是{i}
- </Text );
- }
- return(
- Viewstyle={[styles.container,styles.center]} {spanstyle="font-family:Arial,sans-serif;">arrspan>}
- View }
这样写,RN都会报一个警告,需要你对每个item添加一个key,在Text里添加一个属性key:
copy
Textkey={i}style={{fontSize:20,0); background-color:inherit; font-weight:bold">>
但是这个key有什么作用呢?我们在代码后面加一个console.log输出一下看看结果:
copy
for(vari=0;i ...
- }
console.log(arr);
输出结果显示,arr所有的内容,包括那个key:
看到key和那个props了吗,我们可在未渲染之前,根据要求再次更改array里面<Text>的属性。我们现在来改一改试试看!
先看看上面代码运行的效果:
然后我们在for之后这么改看看结果如何:
copy
arr.length;i++){
- if(arr[i].key==2){
- arr[i].props.style.fontSize=40;
- arr[i].props.style.color='green';
- arr[i].props.children[0]='改变了哦';
- }
-
结果我们可以看到,中间那个key等于2的已经改变了哦。
既然这样,那我们继续改一下,把这个arr改为这个组件的一个属性:
copy
constructor(props){
- super(props);
- this.state={
- blnUpdate:false,
- };
- this.testArr=[];
- this.testArr.push(
- onPress={this.changeChild.bind(this,i)} console.log(this.testArr);
- }
定义在constructor里面,并且附初始值,我们还绑定了一个按键响应, 可以看到临时变化。
另外加一个state变量,用于刷新render(为什么这么做,是RN的刷新机制,需要调用this.setState才会调用,所以弄了一个bln值,而不是把arr放在state里面
然后在绑定还按钮回调中这样做:
copy
changeChild(key){
- console.log(key);
- if(this.testArr[key].props.children[0]=='我变了'){
- this.testArr[key].props.style={fontSize:20,color:'red'};
- this.testArr[key].props.children[0]='这是';
- }else{
- this.testArr[key].props.style={fontSize:30,color:'green'};
- this.testArr[key].props.children[0]='我变了';
- //这里要说说text的结构,如果text是纯文字,children就只有一个,如果中间夹杂着其他变量,react是将text分段保存的。
- this.setUpdate();
- }
setUpdate(){
- this.setState({
- blnUpdate:!this.state.blnUpdate
- });
- 这样我们来看效果:
点击之前:
点击之后:
哈哈,都变了哦!!不过这样做有点延时。其实改变渲染之后的东西,在学习RN之后会有一个专门的参数可供使用,就是每个组件的自带属性ref,在上面的截图我们也看到了,现在ref是null,因为没有设置,如果要使用需要这样做:
copy
Textkey={i}ref={'text'+i}style={{fontSize:20,0); background-color:inherit; font-weight:bold">>
然后使用的时候就是this.refs.text0.xxx,这个RN给我们提供一个很有用的函数,this.refs.text0.setNativeProps({style:{xxx},xxx:xxx}),这个是直接改变原生组件的属性,是不会经过render的,有时候可以提高性能。
不过这个ref有个缺点,它必须要在render之后才会产生,也就是一开始初始化后,使用this.refs.text0 会报错,这点一定要弄清楚哦!
bind
renderAllButtons(){
var allBtns = [];
titles=['拍照','视频','开机','照明']
for(var i=0 ;i<4;i++){
let title = titles[i];
allBtns.push(
<View key={i} style={styles.autoViewStyle}>
<TouchableOpacity style={styles.buttonStyle} onPress={this._pressBtn.bind(this,i)}>
<Text style={styles.textsStyle}>{title}</Text>
</TouchableOpacity>
</View>
);
}
_pressBtn(i){
console.log(i)
} (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|