这部分是我觉得最难理解的区块,透过父传子的概念可以将手上的资料活用到什麽程度?也可以将目前所拥有的state做什麽改变?
this.props.prop-Name
取得从父层传递来的值在使用function与ES6的语法时,getDefaultProps()
会被定义到Component上的一个属性
class Amazing extends React.Component {
// ...
}
Amazing.defaultProps = {
name: 'Mary'
};
//定义到name上
定义: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』,不然会出错!
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'));
this.setState({ color: newColor });
每当调用 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>;
}
}
<仍有资料尚未整理完整,尽快补齐~>
>>: [Day 2] Leetcode 206. Reverse Linked List (C++)
sed sed (Stream Editor), 相较於之前的grep、awk都比较篇查找排版工具,...
如何在冷冰冰程序语言中参杂一些有趣的东西~身为新手的我每次写程序难免BUG充斥字里行间,因此减少Bu...
开分支 具体上要开那些branch呢? 我习惯大致简化分成三种 master 上到productio...
转换一下, 来谈谈PM的日常, 还有其他工作类型, 例如像是产业研究分析的任务, 尤其是针对想要选...
今日练习档 ԅ( ¯་། ¯ԅ) 经过昨天详细的介绍SUM家族後,今天理所当然要介绍与其相似的AVE...