您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“React RenderProps模式如何運(yùn)用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“React RenderProps模式如何運(yùn)用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
上代碼:
import React, { Component } from 'react' import './index.css' export default class Parent extends Component { render() { return ( <div className="parent"> <h4>我是Parent組件</h4> <A/> </div> ) } } class A extends Component { render() { console.log(this.props); return ( <div className="a"> <h4>我是A組件</h4> </div> ) } }
結(jié)果很簡單就能猜到
改一下呢?
import React, { Component } from 'react' import './index.css' export default class Parent extends Component { render() { return ( <div className="parent"> <h4>我是Parent組件</h4> <A>Hello !</A> </div> ) } } class A extends Component { render() { console.log(this.props); return ( <div className="a"> <h4>我是A組件</h4> </div> ) } }
頁面是沒有現(xiàn)實(shí)Hello !的,但是之前一次的封裝NaLink也有傳遞過標(biāo)簽體內(nèi)容的,在子組件的props中,children:(內(nèi)容)
所以A組件想要展示傳遞的標(biāo)簽體內(nèi)容的話,還要改一下A組件
class A extends Component { render() { console.log(this.props); return ( <div className="a"> <h4>我是A組件</h4> {this.props.children} </div> ) } }
import React, { Component } from 'react' import './index.css' export default class Parent extends Component { render() { return ( <div className="parent"> <h4>我是Parent組件</h4> <A> <B/> </A> </div> ) } } class A extends Component { state ={ name:'Mike'} render() { console.log(this.props); return ( <div className="a"> <h4>我是A組件</h4> {this.props.children} </div> ) } } class B extends Component { render() { console.log('B--render'); return ( <div className="b"> <h4>我是B組件</h4> </div> ) } }
A,B組件成了父子組件
但是這樣,如果A組件想傳自己的值給B組件,貌似是行不通的
import React, { Component } from 'react' import './index.css' import C from '../1_setState' export default class Parent extends Component { render() { return ( <div className="parent"> <h4>我是Parent組件</h4> <A render={(name) => <B name={name}/>} /> </div> ) } } class A extends Component { state ={ name:'Mike'} render() { const {name} =this.state; console.log(this.props); return ( <div className="a"> <h4>我是A組件</h4> {this.props.render(name)} </div> ) } } class B extends Component { render() { console.log('B--render'); return ( <div className="b"> <h4>我是B組件,接收到的name:{this.props.name}</h4> </div> ) } }
主要是Parent組件和A組件之間調(diào)用要注意:
Parent組件中,render(當(dāng)然可以去其他的名字這里)這樣寫,相當(dāng)于預(yù)留了一個(gè)插槽,如果你需要渲染其他組件(例如例子中的B組件),在A組件中調(diào)用this.props.render()就可以渲染出B組件,不寫的話就不會(huì)渲染出B組件。
讀到這里,這篇“React RenderProps模式如何運(yùn)用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。