前端:react筆記(貳): react 定義compont, 定義元素 props 介紹

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import './App.css';

import App from './App';

import * as serviceWorker from './serviceWorker';

//定義 元素

const ele = <h1 className="tes" >hello world</h1>; //style = {{textAlign:"center"}}

const el = React.createElement(

'h1',

{className:'tes'},

'hello red'

)

ReactDOM.render(ele,

document.getElementById('root')

);


 

//update dom

//props: 傳入function的任意參數

// function Clock(prop){

// return (

// <div>

// <h1>hello</h1>

// <h2>now:{prop.date.toLocaleTimeString()}</h2>

// </div>

// )

// }

//es6 語法 推薦 定義組件必須 以大寫名字開頭

class Clock extends React.Component{

render(){

return(

<div>hello</div>,

<h2>now: {this.props.date.toLocaleTimeString()}</h2>

);

}

}

//使用組件

// function tick(){

// ReactDOM.render(

// <Clock date={new Date()}/>,

// document.getElementById('interval')

// )

// }

// setInterval(tick,3000);

class Welcome extends React.Component {

render() {

return <h1>Hello, {this.props.name}</h1>;

}

}

 

//多次使用

class Ticks extends React.Component{

render(){

return (

<div> //沒有div框起來 默認只顯示一個組件, 不知道爲什麼

<Welcome name="ssssssssssssssssssssssssssssssssssssssssss"></Welcome>,

<Clock date={new Date()}/>

</div>

// "aa" 不放在div裏 只顯示aa

);

}

}

ReactDOM.render(

<Ticks />,

document.getElementById('interval')

);

//官網實例


 

// class Apps extends React.Component{

// render(){return (

// <div>

// <Welcome name="Sara" />

// <Welcome name="Cahal" />

// <Welcome name="Edite" />

// </div>

// );

// }}

// ReactDOM.render(

// <Apps />,

// document.getElementById('interval')

// );




 

//純函數:

//無論是使用函數或是類來聲明一個組件,它決不能修改它自己的props。來看這個sum函數:

 

function sum(a, b) {

return a + b;

}

// 類似於上面的這種函數稱爲“純函數”,它沒有改變它自己的輸入值,當傳入的值相同時,總是會返回相同的結果。

 

// 與之相對的是非純函數,它會改變它自身的輸入值:

 

// React是非常靈活的,但它也有一個嚴格的規則:

 

// 所有的React組件必須像純函數那樣使用它們的props。

function withdraw(account, amount) {

account.total -= amount;

}

/*數組實現 使用{} 來在html元素等中解析變量 等*/

const array = [

<Ticks/>,

<Welcome name="arrays"/>

]

ReactDOM.render(

<div>{array}</div>,

document.getElementById('interval')

);


 

// If you want your app to work offline and load faster, you can change

// unregister() to register() below. Note this comes with some pitfalls.

// Learn more about service workers: https://bit.ly/CRA-PWA

serviceWorker.unregister();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章