加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

state和props的区别__react

发布时间:2020-12-15 06:48:25 所属栏目:百科 来源:网络整理
导读:首先说明: state和props是每个组件都有的 其次: state可变,但props不可变(这是官网给出的说法) 但实操过程中,state的确可变,但props也可以变,是不是fb搞错了? 当然不是! 这里的可变与不可变,说的是改变后,是否会重新渲染当前组件. 可变对应的是组件会重新渲

首先说明: 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

综上所述,也就不难理解这两者之间的区别了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读