react 能实现插槽传参么

类似于vue 中
插槽 <slot name="aa" index="1">
使用
<div v-slot:aa="data" >{{data.index}}</div>
可以拿到 index的值

react 中props.children可以实现么

阅读 3.4k
2 个回答

1、cloneElement

<>
  {
    // children 不是数组我们需要用 React.Children.map 来遍历
    // 或者把它转成数组
    React.Children.map(children, (child) => {
      if (!React.isValidElement(child)) {
        return null
      }
      // 这里我们通常还会判断 child 的类型来确定是不是要传递相应的数据,这里我就不做了
      const childProps = {
        ...child.props,
        a: 1, // 其他的一些参数
      }
      return React.cloneElement(child, childProps)
    })
  }
</>

2、renderProps/renderCallback

// Parent
<>
  {children(xxx)}
</>
// Use
<Parent>
  {(xxx) => <Child a={xxx} /> }
</Parent>

3、Context或者其他状态管理工具

可以使用你说的props.children
也可以自定定义一个参数类型为ReactNode然后再组件内直接放到你想要放到的位置就好来了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题