文章

React Props Children 混合插槽

React Props Children 混合插槽

当多种 children 一起输入时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function Container(props) {
  const defaultProps = {
    name: "alen",
    msg: "hello",
  }

  return props.children.map((item) => {
    // 通过判断 clone 混入props
    if (React.isValidElement(item)) {
      return React.cloneElement(item, { ...defaultProps })
    } else if (typeof item === "function") {
      return item(defaultProps)
    } else {
      return null
    }
  })
}

function Child(props) {
  return <div>{props.name + props.msg} </div>
}

function App() {
  return (
    <Container>
      // 多种方式混入
      <Child />
      {(props) => <Child {...props} />}
    </Container>
  )
}

render(<App />, document.getElementById("root"))
本文由作者按照 CC BY 4.0 进行授权