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即为新值,外部想传入的值!如此,子组件就获取了外界传来的参数。
简陋的界面
控制时钟启动、暂停、显示、隐藏
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的props和state
- react教程(一)——react优势以及组件、state、props介绍
- react-native的props和state的使用
- 通过props和state实现React子父组件传参
- React Native - (二) Props属性和State状态
- ReactNative学习十三-Props和State
- React中state和props
- React中state与props介绍与比较
- react系列(4)props和state介绍
- [React-Native]Props和State
- React 深入系列3:Props 和 State
- React中的state和props分析
- ReactNative之从HelloWorld中看环境搭建、组件封装、Props及State
- 浅谈React的props和state
- 一张图读懂react的state和props之间的关系
- react的数据载体state、props、context
- React 疑难点-Props和State的区别
- React中state与props介绍与比较
- [置顶] React和Redux 之间的依赖注入connect(mapStateToProps、mapDispatchToProps)
- React中state和props的区别