state和props的区别__react
来源:互联网 发布:测试反应力软件 编辑:程序博客网 时间:2024/05/22 17:09
首先说明: state和props是每个组件都有的
其次: state可变, 但props不可变(这是官网给出的说法)
但实操过程中, state的确可变, 但props也可以变, 是不是fb搞错了? 当然不是!
这里的可变与不可变, 说的是改变后, 是否会重新渲染当前组件. 可变对应的是组件会重新渲染, 不可变(props)是不会渲染的.
至于原因, 则与内部实现机制有关: 每次用 this.setState({test: "test"}) //只能这样更改state
改变state后, 都会触发render函数, 以至于渲染当前组件;
众所周知, react的一个特点就是单向数据流, 也就是说数据只能从父组件向子组件传递, 而这种传递就是依赖于props. 所以当我们改变props时, 无法渲染当前组件, 只能将数据继续向下传递, re-rendering子组件. 所以对于当前组件而言, props是不可变的.
此外, 就字面而言, state是状态, props是属性—即自定义属性, 如下文<ChildComponent boolean />
中的”boolean”.
如下所示: state修改后会渲染当前组件
class ParentComponent extends React.Component{ constructor(props){ super(props) this.state = {boolean: true} this.toggleBool = this.toggleBool.bind(this) } toggleBool(){ let istrue = this.state.boolean this.setState({boolean: !istrue}) } render(){ return( <div> <p>{this.state.boolean? "真": "假"}</p> <botton onClick={this.toggleBool}>切换状态</button> </div> ) }}export default ParentComponent
如下所示: props修改后会渲染子组件
class ChildComponent extends React.Component{ constructor(props){ super(props) } render(){ return( <h3>{this.props.boolean? "么么哒": "呵呵哒"}</h3> ) }}class ParentComponent extends React.Component{ constructor(props){ super(props) this.state = {boolean: true} this.toggleBool = this.toggleBool.bind(this) } toggleBool(){ let istrue = this.state.boolean this.setState({boolean: !istrue}) } render(){ return( <div> <p>{this.state.boolean? "真": "假"}</p> <botton onClick={this.toggleBool}>切换状态</button> <ChildComponent boolean={this.state.boolean} /> /*这个boolean就是props*/ </div> ) }}export default ParentComponent
综上所述, 也就不难理解这两者之间的区别了.
阅读全文
0 0
- state和props的区别__react
- props和state的区别
- React props和state的区别
- React props和state的区别
- props与state的区别
- React的props和state
- React 疑难点-Props和State的区别
- react中 state 和 props 主要的区别
- 浅谈React的props和state
- props和state
- props和state
- React Native State和Props
- [React-Native]Props和State
- React中的props和state
- React中的props和state
- react-native的props和state的使用
- reactjs中props和state最佳实践
- ReactNative学习十三-Props和State
- Traceback (most recent call last): File "/usr/bin/firewall-cmd", line 24, in <module> from gi.
- WebApi接口返回json,xml,text纯文本等
- 笔记(显示实现接口,实现IComparable,IComparer接口来排序)
- CentOS7 LAMP环境搭建
- spring IOC三种机制
- state和props的区别__react
- SHELL脚本编程进阶(一)
- 使用原生的java类进行URL解析
- 指针与引用的区别
- erlang的re模块
- AngularJS
- 优秀工具介绍——angular-loading-bar
- [mysql]ERROR 1364 (HY000): Field 'ssl_cipher' doesn't have a default value
- hibernate 级联查询报错