当前位置:   article > 正文

React中Props和state区别_props & state

props & state

Props和state

1、和props相关
  • 只读,不准修改
  • componentWillReceiveProps / 生命周期
  • propTypes
  • defaultProps
  • children
2、类型检查
import PropTypes from 'prop-types';

List.propTypes = {
    list:PropTypes.array/object/number/string
}
  • 1
  • 2
  • 3
  • 4
  • 5

props和defaultProps

props可以传入: 值,组件,函数

定义默认的props

 class Header extends Component {
  constructor(props){
    super(props)
  }
  // static defaultProps = {
  //   dis:'我是默认的props'
  // }
  render(){

    return (
      <header>header</header>
    )
  }
}
Header.defaultProps = {
  dis:'我是默认的props'
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

props和state

props 父传入

state自身状态

发生变化时会触发render,视图更新

state

state的更改

更改state的方法

//setState为**异步**操作,第二个参数为回掉,在更改state后执行,可在此获取更改后的state的值 
this.setState({
     title:'我是更改后的值'
 },()=>{
     console.log(this.state.title)      
 });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/63376
推荐阅读
相关标签
  

闽ICP备14008679号