RN 认识state 、props

认识RN中的state

@在RN中,系统会持续监控state,组件用state作为数据来源,当state属性值发生改变时,组件就会发生重绘,触发render()方法,渲染UI界面。数据变化后调用this.setState()改变state属性值来更新界面(非及时)。

$state是做什么的

1、主要是用于存储组件自身需要的数据,是组件私有的数据
2、一般通过修改state属性的值来更新数据
3、状态更新是数据合并的过程

$组件什么时候使用state

1、处理用户输入
2、网络数据获取
3、定时更新
4、消息推送等不可预知状态改变的组件

$state的使用规则

1、state任何属性的改变都会导致页面重绘,所以封装可复用组件时应尽量使用props通过组件将数据传到内部
2、在state中,变量是通过计算得到的,使用的时候重新计算,否则就删掉
3、在UI中,可变变量只能是state
4、若要在组件中增加子组件,不要写到state中,应直接写在render方法中

$如何修改state的属性值
this.setState(upDater, callback);
// 参数一:可以是个函数或对象
this.setState({
    autoPlay: true
})
// 如果后面的状态依赖于之前的状态,建议使用 updater 函数(props.step)
this.setState((preState) => {
    return : preState.number + 1;
})

// 参数二:除非 shouldComponentUpdate() 方法返回 falsesetState() 将永远都会引发重新渲染,若shouldComponentUpdate() 方法返回false,通常使用官方推荐的componentDidUpdate()方法
$单向数据流

父组件和子组件不能通过state交互,都是私有的。父组件可以通过state来改变子组件的props。任何有state驱动的数据只会影响到该组件的子组件

<ItemContent onChange={this._textChange.bind(this)} />
_textChange(title,width, height){
    let msg = this.state.msg;
    // 这里可以处理一些业务逻辑
    if(title!= ''){
        this.setState({
            msg: title
        })
    }
    this.setState({
        width:width,
        height:height
    })
}

class ItemContent extends Component {
    constructor(props){
        super(props);
        this.state = {
            msg: '原来的值',
            onChange: this.props.onChange,
        }
    }
    _textChange(event){
        this.setState({
            msg: '封装的一个组件'
        })
        if(this.state.onChange === 'function'){
            this.state.onChange(this.props.title, this.event.contentSize.width,this.event.contentSize.height)
        }
    }
    render(){
        return (
            <View>
                <TextInput 
                    ……
                    title = {'属性'}
                    onChange = {this._textChange.bind(this)}
                />
            </View>
        )
    }
}

认识RN中的props

@在RN中props在父组件中指定的,在整个生命周期中不会改变,父组件传递给子组件
可以通过声明defaultProps指定默认值,声明propTypes可以控制属性类型,但是在正式发布的app中propTypes不会进行属性检查

// 父组件的属性值们
  let params = {name: '小红', age: '18', msg: '父组件的属性'}
  <Component {...params} />
// 子组件取值
  render(){
      let {name, msg} = params
     <View>
        <Text>{name} {msg}</Text>
    </View>
  }

猜你喜欢

转载自blog.csdn.net/snow51/article/details/80512808
今日推荐