游客发表

React中的函数式插槽,你明白了吗?

发帖时间:2025-11-04 19:10:40

朋友们,数式好久不见,插槽最近搬家,明白通勤时间从1小时变成三小时,数式花了一两个月终于适应了,插槽所以有空我又来更新文章了,明白今天分享 React 开发中遇到的数式具名插槽的函数用法

你可能见过下面的写法。通常情况下,插槽我们都会使用 children 属性实现类似Vue的明白默认插槽功能。

复制const Component = ({ value,数式 children }) => { return <> {value} {children} </> } function App() { return <Component value="hello">world</Component> }1.2.3.4.5.6.7.8.9.10.

上面使用了隐藏的 children 属性,我们可以显示的插槽指定它

复制function App() { return <Component value="hello" children="world" /> }1.2.3.

children 属性默认是 jsx 表达式,不是云服务器提供商明白时,需要做额外的数式解析,否则会报错

但是插槽当 children 属性是函数时,就会发生质的明白变化。

复制const Component = ({value, children}) => { return <>{children(value)}</> } const renderChildren = (value) => { return value.join(--) } function App() { return ( <Component value={["hello", world]} children={renderChildren} /> ) }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.

图片

显示的指定 children 属性时,相当于具名插槽,所以我们未必需要使用 children 字段,或许你可以使用reader更合适

如果你不喜欢显示的声明 children 属性,那么可以这么写:

复制function App() { return ( <Component value={["hello", world]}> {(value) => { return value.join(--) }} </Component> ) }1.2.3.4.5.6.7.8.9.

这种写法似乎有点熟悉,没错,React 官方也这么干过,你来看看这个例子。服务器租用

复制const Context = createContext({name: 萌萌哒草头将军}); export const Provider = Context.Provider; export const Consumer = Context.Consumer; // 你的组件,假设已经被 Provider 包裹了 function Component() { return ( <Consumer>{ ({ name }) => <h1>name: { name }</h1> }</Consumer> ); }1.2.3.4.5.6.7.8.9.10.11.12.13.

相似的还有一些第三方库,比如 antd 的 <Form.List />。这里就不一一举例子了。

虽然这种写法看起来很奇怪,但是可以极大地提高组件的灵活性。或者说,这是一种超级加强的插槽写法。因为,我们可以在组件外自定义渲染逻辑。

免费信息发布网

    热门排行

    友情链接