< 关於 React: 开始打地基| props、state >

本章内容
  • prop的传递重点
    • 宣告预设的props
    • 如何使用prop
  • this.state
    • 从另外一个函示中叫出this.setState
    • 使用 this.setState 怎麽一直自动更新?

前言:

这部分是我觉得最难理解的区块,透过父传子的概念可以将手上的资料活用到什麽程度?也可以将目前所拥有的state做什麽改变?


prop的传递重点

  1. 通过Component传递prop,同时可以将属性(attribute)同时传递至子层
  2. 在子层可以透过,this.props.prop-Name取得从父层传递来的值
  3. 使用prop决定要展示的内容
  4. 将事件处理方式作为prop传递
  5. 接受prop事件处理并将其附在其他监听事件上
  6. 根据已经命名事件处理和事件处理程序属性相对应即可执行
  7. this.props.children 即是props内的内容
  8. getDefaultProps()

宣告一个预设的props

在使用function与ES6的语法时,getDefaultProps()会被定义到Component上的一个属性

class Amazing extends React.Component {
  // ...
}

Amazing.defaultProps = {
  name: 'Mary'
};
//定义到name上

this.state

定义:Dynamic information 可以改变的资料
有两种方式可以拿到component中变动的资料:prop、state

prop vs. state 不同处
prop 在component 外部定义
state 在component内部定义

?写法:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { mood: 'decent' };
  }
 
  render() {
    return <div></div>;
  }
}
 
<Example />

解释:

第四行 this.state 需要等於一个物件
constructor、super是ES6的写法,不单单只是写在React中

说明

在React component 中constructors在建立时,会使用『super』,不然会出错!

从另外一个函示中叫出this.setState

import React from 'react';
import ReactDOM from 'react-dom';

const green = '#39D1B4';
const yellow = '#FFD712';

class Toggle extends React.Component {
  constructor(props){
    super(props);
    this.state = { color: green };
    this.changeColor = this.changeColor.bind(this);
  }
  
  changeColor() {
    const newColor = this.state.color == green ? yellow : green;
    this.setState({ color: newColor });
  }
  
  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change my color
        </h1>
        <button onClick={this.changeColor}>
  			    Change color
				</button>
      </div>
    );
  }
}

ReactDOM.render(<Toggle />, document.getElementById('app'));

解释:

  1. 透过25行的 button 触发click事件
  2. 监听21行中的 背景色切换
  3. 监听的定义在14-16行内
  4. 整个事件主调用在第16行
    this.setState({ color: newColor });
  5. 在12行中,定义切换的颜色

使用 this.setState 怎麽一直自动更新?

每当调用 this.setState() 时,一旦状态发生变化,this.setState() 就会自动调用 .render()。

所以,setState(),==不可以==呼叫render()中的函数,否则会造成infinite loop ➰

class BadComponent extends React.Component {
  constructor(props) {
    super(props);
    this.count = 0;
  }
  render() {
    // Don't do this! This is bad!
    this.setState({ count: this.state.count + 1 });
    return <div>The count is {this.state.count}</div>;
  }
}

<仍有资料尚未整理完整,尽快补齐~>


<<:  DAY7 - 图

>>:  [Day 2] Leetcode 206. Reverse Linked List (C++)

sed - 简介 读取编辑文字档的好工具

sed sed (Stream Editor), 相较於之前的grep、awk都比较篇查找排版工具,...

# 番外: 法喜充满,bug占满?? 当程序码遇到信仰

如何在冷冰冰程序语言中参杂一些有趣的东西~身为新手的我每次写程序难免BUG充斥字里行间,因此减少Bu...

Day 5 : Git 多人协作

开分支 具体上要开那些branch呢? 我习惯大致简化分成三种 master 上到productio...

Day 18 - 产业研究分析浅谈

转换一下, 来谈谈PM的日常, 还有其他工作类型, 例如像是产业研究分析的任务, 尤其是针对想要选...

Day-23 你没想到的Excel average知识

今日练习档 ԅ( ¯་། ¯ԅ) 经过昨天详细的介绍SUM家族後,今天理所当然要介绍与其相似的AVE...