状态的介绍

image.png
对于 React 来讲一切的变化都是基于状态的,如果说你在其他某个地方修改了这个状态,那么在你最初定义这个地方的状态也会跟着被修改,这个是 React 非常核心的技能点。

image.png
上面这个是说例如:少年、中年、老年这样按照年龄段的多种状态,每个状态相对应的里面的内容也应该发生一个变化

image.png
状态是需要我们用程序来控制的

image.png
状态驱动 render 更新的过程

状态的用法

image.png
ES5 & ES6

源码
  1. //ES5 写法
  2. var HelloMassage = React.createClass({
  3. //设置默认属性
  4. getDefaultProps: function() {
  5. return {
  6. name: "123"
  7. // name: 1//由于在下面指定了类型为 string 这里如果设置为 1 的话就会报错
  8. };
  9. },
  10. //属性校验器,表示必须是 string
  11. propTypes: {
  12. name: React.PropTypes.string,
  13. },
  14. //初始化状态
  15. getInitialState: function() {
  16. return {
  17. isLoading: false
  18. };
  19. },
  20. //增加一个修改 state 的事件
  21. handle: function() {
  22. console.log(this);
  23. this.setState({
  24. isLoading: true, //这里修改之后全局都会跟着改变下面在对 isLoading 做三元判断 render 的相应内容也会自动的跟着改变,他会在全局去监控这个 state
  25. });
  26. console.log("状态修改成功");
  27. },
  28. render: function() {
  29. return (
  30. // <div>{this.props.name}</div>
  31. //调用一个对象多个属性的写法
  32. // <div>Hello,{this.props.name1},{this.props.name2}</div>
  33. <div>
  34. {/*通过状态来 返回相应的内容*/}
  35. {!this.state.isLoading ? <h1>loading...</h1> : <h1>ok</h1>}
  36. { /*
  37. *调取 name 属性的默认值
  38. *增加点击事件
  39. */ }
  40. <div onClick={this.handle}>Hello,{this.props.name}</div>
  41. </div>
  42. );
  43. }
  44. });
  45. //传递一个对象
  46. var props = {
  47. name1: "xiaochuan",
  48. name2: "xiaoming"
  49. };
  50. ReactDOM.render(
  51. // <HelloMassage name="xiaochuan" />,
  52. //传递一个对象的写法
  53. <HelloMassage {...props} />, //Hello,xiaochuan,xiaoming
  54. document.getElementById("example")
  55. );
  1. //ES6 写法
  2. "use strict";
  3. class HelloMassage extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. title: props.title + 200
  8. }
  9. }
  10. render() {
  11. //数组的调用方法
  12. // var commentNode = this.props.name.map(function(datavalue, datakey) {
  13. // return <div key={datakey}>Hello,{datavalue}!</div>
  14. // });
  15. return (
  16. //数组的调用方法
  17. // <div>{commentNode}</div>
  18. // <h1 className="h1">{this.props.name}</h1>
  19. <div>
  20. {/*测试默认属性*/}
  21. <h1>{this.props.title}</h1>
  22. {/*测试获取 state 属性的参数值*/}
  23. <h1>{this.state.title}</h1>
  24. </div>
  25. )
  26. }
  27. }
  28. //通过变量传递
  29. var data = "通过一个变量传递属性";
  30. //属性校验器,表示必须是 string
  31. HelloMassage.propTypes = {
  32. title: React.PropTypes.string,
  33. };
  34. //设置默认属性
  35. HelloMassage.defaultProps = {
  36. title: "321"
  37. };
  38. ReactDOM.render(
  39. // <HelloMassage name="xiaochuan" />,//xiaochuan
  40. // <HelloMassage name={123} />,//123
  41. // <HelloMassage name={"孙小川"} />, //孙小川
  42. // <HelloMassage name={["1","2","3"]} />, //需要在上面使用 map 方法映射键值对
  43. //数组输出:Hello, 1! Hello, 2! Hello, 3!
  44. // <HelloMassage name={data} />,
  45. //测试默认属性
  46. <HelloMassage />,
  47. document.getElementById("example")
  48. );