react元件的拆分與傳值

2021-10-02 05:40:38 字數 2828 閱讀 7303

父元件通過屬性的形式向子元件傳值

子元件想要和父元件通訊,呼叫父元件傳遞過來的方法

單項資料流:父元件可以向子元件傳值,但是子元件一定不能直接的去改變這個值。

父元件:

import react ,

from

'react'

;import todoitem from

'./todoitem'

;import

'./style.css'

;//react 響應式

//定義元件

class

todolist

extends

component

}handleinputchange

(e))

}handlekeyup

(e))}}

handleitemclick

(index));

}getlistitems()

index =

key=

// 父元件還可以給子元件傳遞方法

deletefunction=

/>)}

)}//render函式決定元件渲染內容

render()

引起來 */

}'myinput'

>請輸入內容:<

/label>

id =

'myinput'

classname =

'input'

value =

// handleinputchang函式的this指向的是undefined,需要使用bind將this指向變更成這個元件的指向,

// 也就是指向render()函式的指向,又由於render函式指向的是元件,也就是說handleinputchange也指向了這個元件

onchange =

//當按任意乙個鍵,鍵彈起來的時候繫結的事件

onkeyup =

/>

<

/ul>

<

/fragment>);

}}//在index引用之前要先將totolist暴露出去

//也就是把自己暴露出去,供別人使用

export

default todolist;

子元件

import react,

from

'react'

;class

todoitem

extends

component

handleitemclick()

=this

.props;

deletefunction

(index);}

render()

=this

.props;

//等價於 const content = this.props.content;

return

>

<

/li>}}

export

default todoitem;

小例子:實現一次傳值過程,把hello world顯示在頁面上

建立乙個父元件father

建立乙個子元件son

子元件接收父元件的屬性名content,content的屬性值為"hello world"

把hello world顯示在頁面上

實現思路建議:

第一步:首先我們要定義父元件和子元件且分清,誰是父元件,誰是子元件

第二步:需要把子元件引入到父元件所在的檔案當中

第三步:引入子元件import son from './son';

第四步:首先我們要在引入過來的子元件上去自定義乙個屬性,比如content,接著就是我們要把傳入自組建的值寫入到content屬性值

第五步:那麼接下來,我們要做的就是,如何去接收父元件傳遞過來的值,這裡就要用到props屬性,他的作用就是接收傳值。這樣,就接收到父元件傳遞過來的值,其中,this.props.content中的props後面的content就是在父元件當中,在子元件上自定義的content屬性

father.js

import react,

from

'react'

;import son from

'./son'

;class

father

extends

component

}export

default father;

son.js

import react,

from

'react'

;class

sonextends

component

render()

<

/div>)}

}export

default son;

index.js

import react from

'react'

;import reactdom from

'react-dom'

;import father from

'./father'

;reactdom.

render

(>

,document.

getelementbyid

('root'))

;

React元件傳值

父元件向子元件傳值 通過父元件的props屬性向子元件傳值 子元件 children.js import react,from react export default class children extends component render 父元件 parent.js import reac...

react 元件傳值

通過props實現 父元件parent import react from react import child from children class comment extends react.component render export default comment 子元件children...

React元件傳值

react的單向資料流與元件間的溝通。首先,我認為使用react的最大好處在於 功能元件化,遵守前端可維護的原則。先介紹單向資料流吧。react單向資料流 react是單向資料流,資料主要從父節點傳遞到子節點 通過props 如果頂層 父級 的某個props改變了,react會重渲染所有的子節點。剛...