朋友们,好久不见,最近搬家,通勤时间从1小时变成三小时,花了一两个月终于适应了,所以有空我又来更新文章了,今天分享 React 开发中遇到的具名插槽的函数用法
你可能见过下面的写法。通常情况下,我们都会使用 children 属性实现类似Vue的默认插槽功能。
const Component=({value,children })=>{return<>{value} {children}</>}functionApp(){return<Componentvalue="hello">world</Component>}
上面使用了隐藏的 children 属性,我们可以显示的指定它
functionApp(){return<Componentvalue="hello"children="world"/>}
children 属性默认是 jsx 表达式,不是时,需要做额外的解析,否则会报错
但是当 children 属性是函数时,就会发生质的变化。
const Component=({value,children})=>{return<>{children(value)}</>} const renderChildren=(value)=>{returnvalue.join('--')}functionApp(){return(<Componentvalue={["hello",'world']} children={renderChildren}/>)}
图片
显示的指定 children 属性时,相当于具名插槽,所以我们未必需要使用 children 字段,或许你可以使用reader更合适
如果你不喜欢显示的声明 children 属性,那么可以这么写:
functionApp(){return(<Componentvalue={["hello",'world']}>{(value)=>{returnvalue.join('--')}}</Component>)}
这种写法似乎有点熟悉,没错,React 官方也这么干过,你来看看这个例子。
const Context=createContext({name:'萌萌哒草头将军'});export const Provider=Context.Provider;export const Consumer=Context.Consumer;// 你的组件,假设已经被 Provider 包裹了functionComponent(){return(<Consumer>{({ name })=><h1>name: { name }</h1>}</Consumer>);}
相似的还有一些第三方库,比如 antd 的 <Form.List />。这里就不一一举例子了。
虽然这种写法看起来很奇怪,但是可以极大地提高组件的灵活性。或者说,这是一种超级加强的插槽写法。因为,我们可以在组件外自定义渲染逻辑。