您的位置:首页 > Web前端 > React

React中的props和state

2017-11-27 22:37 387 查看
props意为属性,只可父组件改变子组件的props,而子组件不能自更新,props是子组件暴露给外部的公有接口

state意为状态,所谓的状态就是一种标记,设计用来控制某种逻辑,类似于后台语言中的flag,全局的私有变量,外部不能访问,state的改变会被render()函数自动捕捉到,当然state改变后是否执行render,还取决于bool shouldComponentUpdate(nextProps, nextState) 返回false则不会重新渲染。

改变state的方法,setState({

……

})

不能直接给state重新赋值

那么问题来了 ,外部只能控制props,怎么让子组件捕捉到props发生改变了呢?

void componentWillReceiveProps(nextProps)

nextProps即为新值,外部想传入的值!如此,子组件就获取了外界传来的参数。

父组件 ClockApp

import React, { Component } from 'react'
import Clock from "./Clock"

export default class ClockApp extends Component {
constructor(props) {
super(props);
this.state = {
isRun: true,
isShow: true
}
}

onValueChange(event){
if(event.target.name==="run") this.setState({
isRun:!this.state.isRun
})
else if(event.target.name==="show") this.setState({
isShow:!this.state.isShow
})
}
render() {
return (
<div>

<input type="checkbox" onChange={this.onValueChange.bind(this)} name="run"/><span>{this.state.isRun?"开启":"停止"}</span><br/>
<input type="checkbox" onChange={this.onValueChange.bind(this)} name="show"/><span>{this.state.isShow?"显示":"隐藏"}</span><br/>
<Clock isShow={this.state.isShow}  isRun={this.state.isRun}/>
</div>

);
}

}


子组件Clock

import React, { Component } from "react"

export default class Clock extends Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}

componentWillMount () {
this.timer = setInterval(() => {
this.setState({ date: new Date() })
}, 1000)
}

componentWillUnmount() {
clearInterval(this.timer);
}

componentWillReceiveProps(nextProps){
if(nextProps.isRun){
clearInterval(this.timer);
this.timer = setInterval(() => {
this.setState({ date: new Date() })
}, 1000)
}
else
clearInterval(this.timer);
}

render() {
var rStyle = {
display:this.props.isShow?"block":"none"
};
return (
<div style={rStyle}>
<h2>现在时间</h2>
<span >{this.state.date.toLocaleTimeString()}</span>
</div>
);
}

}


简陋的界面



控制时钟启动、暂停、显示、隐藏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  React state props