跳转指定位置
ReactNative详解生命周期
前言
- 1、数据变化怎么通知React(以按钮更新文本为例)
常用的通知React数据变化的方法是调用**setState(data,callback)**,这个方法会合并data到this.state,并重新渲染组件。渲染完成后,调用可选的callback回调。大部分情况不需要提供callback,因为React会负责吧界面更新到最新状态。
详情查看:附一:StateEasyPage.js 与 StateNormalPage.js
- 2、怎么给组件添加属性、设置默认值,并对默认值设置类型检查
一、了解state作用
1、this.setState({xxx:’’}) 与 this.state.xxx=’’
| 类型 |
this.state.xxx=’’ |
this.setState({xxx:’’}) |
| 作用 |
this.state通常是用来初始化state的 |
this.setstate是用来修改state值的 |
| 注意 |
再次调用时候,之前的state会被覆盖掉 |
再次调用时候,只会替换掉相应的state值 |
|
|
|
所以,自定义组件的时候,因为其需要传的参数是会被变化的,所以,我们在自定义组件中,不能使用state来更新,而是自定义组件中使用props,结合外部调用它的来处理。
2、认识state原理
2.1、this.setState({})
this.setState({})会触发render方法,重新渲染界面。而this.state.xxx=’’ 不会重新加载UI。
this.setState({})是异步的
三、类型判断
参考文章:
附
附一:StateEasyPage.js 与 StateNormalPage.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| //StateEasyPage.js import React, { Component } from 'react'; import { View, Button, Text } from 'react-native';
export default class StateEasyPage extends Component { constructor(props) { super(props); this.state = { showText: "旧标题" }; }
render() { return ( <View> <Button title={"点击切换标题"} onPress={()=>{ this.setState({ showText: "新标题" }) }} /> <Text>{this.state.showText}</Text> </View> ) } }
|
丰富一下,使其可以来回切换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| //StateNormalPage.js import React, { Component } from 'react'; import { View, Button, Text } from 'react-native';
export default class StateNormalPage extends Component { constructor(props) { super(props); this.state = { showText: "旧标题", isShowNew: false }; }
render() { let currentShowText = this.state.isShowNew ? "新标题" : "旧标题"
return ( <View> <Button title={"点击切换标题"} onPress={()=>{ let isShowNew = !this.state.isShowNew; this.setState({ isShowNew: isShowNew }) }} /> <Text>{currentShowText}</Text> </View> ) } }
|