React开发之Porps和State
2017-05-10 10:39
148 查看
最近项目一直在用React,所以把自己学的东西都总结下来。
前言
在实际开发中,我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。
Props概念:大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props(属性)。
通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。
下面是我写的一个TextInput自定义组件:
State概念:用来更新需要改变的数据。实际开发中,我们一般不会在定时器函数(setInterval、setTimeout等)中来操作State。
一般来说,你需要在constructor中初始化state,然后在需要修改时调用setState方法。
以上编码全部采用ES6规范,ES5已经逐渐被淘汰了,大家以后编码就按照ES6标准写吧,后续会整理一篇ES6规范,期待一下。。。
前言
在实际开发中,我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。
Props概念:大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props(属性)。
通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。
下面是我写的一个TextInput自定义组件:
import React from 'react'; class TextInput extends React.Component{ render () { var {value, placeholder, updateValue} = this.props; return ( <div> <input placeholder={placeholder} value={value} onChange= {(event)=>{updateValue(event.target.value)}}/> </div> ); } } TextInput.propTypes = { value: React.PropTypes.string.isRequired, updateValue: React.PropTypes.func.isRequired, placeholder: React.PropTypes.string }; TextInput.displayName = 'TextInput'; export default TextInput;
State概念:用来更新需要改变的数据。实际开发中,我们一般不会在定时器函数(setInterval、setTimeout等)中来操作State。
一般来说,你需要在constructor中初始化state,然后在需要修改时调用setState方法。
import React, { Component } from 'react'; import { Text, View } from 'react-native'; class Blink extends Component { constructor(props) { super(props); this.state = { showText: true }; // 每1000毫秒对showText状态做一次取反操作 setInterval(() => { this.setState(previousState => { return { showText: !previousState.showText }; }); }, 1000); } render() { // 根据当前showText的值决定是否显示text内容 let display = this.state.showText ? this.props.text : ' '; return ( <Text>{display}</Text> ); } } class BlinkApp extends Component { render() { return ( <View> <Blink text='I love to blink' /> <Blink text='Yes blinking is so great' /> <Blink text='Why did they ever take this out of HTML' /> <Blink text='Look at me look at me look at me' /> </View> ); } }
以上编码全部采用ES6规范,ES5已经逐渐被淘汰了,大家以后编码就按照ES6标准写吧,后续会整理一篇ES6规范,期待一下。。。
相关文章推荐
- 混合开发的大趋势之一React Native State (状态),Style(样式)
- 混合开发的大趋势之一React Native State (状态),Style(样式)
- React Native开发】React Native 基础之Props(属性)与State(状态)使用讲解
- Android开发之InstanceState详解
- ReactNativeiOS(三)开发零碎2 DatePickerIOS propType warning 4个
- 基于react+react-router+redux+socket.io+koa开发一个聊天室
- Android开发之InstanceState详解
- React Native State和Props
- 基于react+react-router+redux+socket.io+koa开发一个聊天室
- React getInitialState desc
- React Native 开发之 (06) JSX
- React + webpack 快速搭建开发环境
- 搭建es6+react开发环境---webpack
- 企业开发--React 中的this使用
- react 开发规范
- 适用于UWP应用开发的开源React Native插件
- 第二章:typescript与js开发react的区别
- 开发中碰到的问题:IllegalStateException: Can not perform this action after onSaveInstanceState
- react开发中遇到的问题
- 前端开发框架简介:angular和react