React缁勪欢璁捐妯″紡-Render-props

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React缁勪欢璁捐妯″紡-Render-props相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e7%99%bb%e5%bd%95' title='鐧诲綍'>鐧诲綍   浣跨敤鏂规硶   power   棰戠巼   涔熶細   鐢ㄦ埛   ons   鍏徃   璇濋   

鍐欎笟鍔℃椂锛屾垜浠粡甯搁渶瑕佹娊璞′竴浜涗娇鐢ㄩ鐜囪緝楂樼殑閫昏緫锛屼絾鏄櫎浜嗛珮闃剁粍浠跺彲浠ユ娊璞¢€昏緫锛孯enderProps涔熸槸涓€绉嶆瘮杈冨ソ鐨勬柟娉曘€?/p>

RenderProps锛岄【鍚嶆€濅箟灏辨槸灏嗙粍浠剁殑props娓叉煋鍑烘潵銆傚疄闄呬笂鏄缁勪欢鐨刾rops鎺ユ敹鍑芥暟锛岀敱鍑芥暟鏉ユ覆鏌撳唴瀹广€傚皢閫氱敤鐨勯€昏緫鎶借薄鍦ㄨ缁勪欢鐨勫唴閮紝鐒跺悗渚濇嵁涓氬姟閫昏緫鏉ヨ皟鐢ㄥ嚱鏁帮紙props鍐呮覆鏌撳唴瀹圭殑鍑芥暟锛夛紝浠庤€岃揪鍒伴噸鐢ㄩ€昏緫鐨勭洰鐨勩€?/p>

 

绠€鍗曞疄鐜?/h3>

鎴戜滑鍏堢湅涓€涓渶绠€鍗曠殑RenderProps妯″紡鐨勫疄鐜帮細

const RenderProps = props => <>
    {props.children(props)}
</>

鍦ㄨ繖閲岋紝RenderProps缁勪欢鐨勫瓙缁勪欢鏄竴涓嚱鏁皃rops.children(props)锛岃€宲rops.children杩斿洖鐨勬槸UI鍏冪礌銆?/p>

浣跨敤鏃剁殑浠g爜濡備笅锛?/p>

<RenderProps>
    {() => <>Hello RenderProps</>}
</RenderProps>

浠ヤ笂鏈綔浠讳綍鐨勪笟鍔¢€昏緫澶勭悊锛屾湁浠€涔堢敤澶勫憿锛熸垜浠彲浠ユ兂鍒帮紝鍙互鍦?RenderProps 缁勪欢涓幓鐢ㄤ唬鐮佹搷鎺ц繑鍥炵殑缁撴灉銆?br>浠ユ渶甯歌鐨勭敤鎴风櫥褰曢€昏緫涓轰緥锛屽笇鏈涘湪鐧婚檰涔嬪悗鎵嶅彲浠ョ湅鍒板唴瀹癸紝鍚﹀垯灞曠ず璇风櫥褰曪細

const Auth = props => {
    const userName = getUserName()
    if (userName) {
        const allProps = {userName, ...props}
        return <>
            {props.children(allProps)}
        </>
    } else {
        return <>璇风櫥褰?span class="hljs-tag"></>
    }
}


<Auth>
    {({userName}) => <>Hello锛亄userName}</>}
</Auth>

props.children(allProps) 灏辩浉褰撲簬Auth缁勪欢宓屽鐨?{userName}) => <>Hello锛亄userName}</>

涓婅竟鐨勪緥瀛愪腑锛岀敤鎴疯嫢宸茬粡鐧婚檰锛実etUserName杩斿洖鐢ㄦ埛鍚嶏紝鍚﹀垯杩斿洖绌恒€傝繖鏍锋垜浠氨鍙互鍒ゆ柇杩斿洖鍝簺鍐呭浜嗐€?br>褰撶劧锛屼笂杈归€氳繃renderProps浼犲叆浜唘serName,杩欏睘浜嶢uth缁勪欢鐨勫寮哄姛鑳姐€?/p>

 

鍑芥暟鍚嶄笉浠呭彲浠ユ槸children

骞虫椂涓€鑸娇鐢ㄧ殑鏃跺€欙紝props.children閮芥槸鍏蜂綋鐨勭粍浠跺疄渚嬶紝浣嗕笂杈圭殑瀹炵幇鏄熀浜庝互鍑芥暟涓哄瓙缁勪欢锛坈hildren(props)锛夛紝琚皟鐢ㄨ繑鍥濽I銆?br>鍚屾牱锛屽彲浠ヨ皟鐢╬rops涓殑浠讳綍鍑芥暟銆傝繕鏄互涓婅竟鐨勯€昏緫涓轰緥锛?/p>

const Auth = props => {
  const userName = "Mike"
  if (userName) {
    const allProps = { userName, ...props }
    return <>{props.login(allProps)}</>
  } else {
    return <>
      {props.noLogin(props)}
    </>
  }
}

浣跨敤鏂规硶濡備笅锛?/p>

<Auth
    login={({userName}) => <h1>Hello {userName}</h1>}
    noLogin={() => <h1>please login</h1>}
  />

杩欓噷锛孉uth缁勪欢鐨刾rops鎺ユ敹涓や釜鍑芥暟锛?strong>login(琛ㄧず宸茬粡鐧诲綍)锛?strong>noLogin(琛ㄦ湭鐧诲綍)锛?br>Auth缁勪欢鍐呴儴锛岄€氳繃鍒ゆ柇鏄惁鐧婚檰鏉ュ喅瀹氭樉绀哄摢涓粍浠躲€?/p>

璧勬簮鎼滅储缃戠珯澶у叏 https://www.renrenfan.com.cn 骞垮窞VI璁捐鍏徃https://www.houdianzi.com

鎬荤粨

render-props浣滀负涓€绉嶆娊璞¢€氱敤閫昏緫鐨勬柟娉曪紝鍏舵湰韬篃浼氶亣鍒板儚楂橀樁缁勪欢閭f牱灞傚眰宓屽鐨勯棶棰樸€?/p>

<GrandFather>
  {Props => {
    <Father>
      {props => {
        <Son {...props} />;
      }}
    </Father>;
  }}
</GrandFather>

浣嗗拰楂橀樁缁勪欢涓嶅悓鐨勬槸锛岀敱浜庢覆鏌撶殑鏄嚱鏁?楂橀樁缁勪欢娓叉煋鐨勬槸缁勪欢)锛屽氨涓哄埄鐢╟ompose鎻愪緵浜嗘満浼氥€備緥濡俽eact-powerplugin銆?/p>

import { compose } from "react-powerplug"

const ComposeComponent = compose(
  <GrandFather />,
  <Father />
)
<ComposeComponent>
  {props => {
    <Son {...props} />;
  }}
<ComposeComponent/>

杩樻湁Epitath涔熸彁渚涗簡涓€绉嶆柊妯″紡鏉ヨВ鍐宠繖涓棶棰樸€傝繖閮ㄥ垎灞曞紑鏉ヨ鐨勮瘽鏄彟涓€涓瘽棰樹簡锛屾垜涔熷湪鎽哥储涓€?/p>

以上是关于React缁勪欢璁捐妯″紡-Render-props的主要内容,如果未能解决你的问题,请参考以下文章

璁捐妯″紡-浠g悊妯″紡

璁捐妯″紡

璁捐妯″紡锛歴tate妯″紡

璁捐妯″紡@绗?5绔狅細浠g悊妯″紡

璁捐妯″紡绯诲垪| 澶栬锛堥棬闈級妯″紡

璁捐妯″紡涔嬬粨鏋勫瀷--瑁呴グ妯″紡