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的主要内容,如果未能解决你的问题,请参考以下文章