当我们会写基本的 Hello World 之後,就可以开始考虑扩展跟重组我们要撰写的程序码了。我们会把一段与其他程序码基本上相异的,而内部彼此有关联的程序码,写成所谓的元件(component),而撰写的方式有两种
function Smile(){
return <div>?</div>;
}
Class Smile extends React.Component {
render() {
Return <div>?</div>;
}
}
知道基本的 Component 的写法之後,就可以练习
1.去拆解或组合并复用元件
2.重复使用元件并带入不同资料,使用 Props,像函数传递参数
function Greet(props) {
return <h1>{props.message}, {props.face}</h1>;
}
const element = (
<div>
<h1>=== Emoji List and Message ===</h1>
<Greet message="LOL" face="?" />
<Greet message="..." face="?" />
<Greet message="No!" face="?" />
</div>);
ReactDOM.render(element, document.getElementById('root'));
以下组合例子(里面使用了map语法,後面会更详细的说明)
function Greet(props) {
return <h1>{props.message}, {props.face}</h1>;
}
function Emotions() {
const emojiList = [{
message: 'LOL',
face: "?"
}, {
message: 'speechless',
face: "?"
}, {
message: 'Shocked',
face: "?"
}]
return (
<div>
<h1>=== Emoji List and Message ===</h1>
{
emojiList.map(item=>{
return <Greet key={item.face} message={item.message} face={item.face} />
})
}
</div>
)
}
ReactDOM.render(<Emotions />, document.getElementById('root'));
什麽是 Pure function?
1.给同样的输入,会得到一样的输出
2.没有副作用
如果 props 可以存取,就会产生副作用。在输出时,「同时」更新了输入。
更多说明可参考 Eric Elliott 的 Master the JavaScript Interview: What is a Pure Function?
以上今天。
参考资料:
https://zh-hant.reactjs.org/docs/components-and-props.html
Master the JavaScript Interview: What is a Pure Function?
<<: EP 10: Passing Data for Navigation in TopStore App - I
进行抽样 & 贝氏分析的基础教学之後,本书的最後一个部分在讨论对「软性事物」的衡量,例如品质...
一、主题内容 虽然知道全端工程师的路不好走,自己目前也还不是很称职,仍想以自己转职的角度、回顾的方式...
将create date的auto_now_add删除 并加入upload相关栏位 DateTime...
在初学Java的时候,常常会有以下的输入输出范例出现: Scanner sc = new Scann...
了解分支的用途後,在合作开发上一定便利许多,但同样地,不是每件事情都顺顺利利,只要有合作的事情,总是...