React 中的"slot"

4,455 阅读1分钟

取自React官网教程

Children in JSX

In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: props.children. There are several different ways to pass children:

在JSX表达式中包含 开始标签 和结束标签,两个标签之间的内容会被当作一个特殊的prop "props.children" 处理,我们有N种不同的方法来传递children:

String Literals

You can put a string between the opening and closing tags and props.children will just be that string. This is useful for many of the built-in HTML elements. For example:

<MyComponent>Hello world!</MyComponent>

JSX Children

You can provide more JSX elements as the children. This is useful for displaying nested components:

<MyContainer>
  <MyFirstComponent />
  <MySecondComponent />
</MyContainer>

JavaScript Expressions as Children

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

Functions as Children

Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things. However, props.children works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as props.children: 通常情况下,Javascript 表达式传入jsx中会被处理成string,一个React element,或者列表。 但是props.children 就像其它prop一样可以传递任何类型的数据 ,不步是React知道如何渲染的种类。例如,如果你有一个自定义组件,你可以使用它一个callback 回调作为props.children

function Repeat(props) {
  let items = [];
  for (let i = 0; i < props.numTimes; i++) {
    items.push(props.children(i));
  }
  return <div>{items}</div>;
}

function ListOfTenThings() {
  return (
    <Repeat numTimes={10}>
      {(index) => <div key={index}>This is item {index} in the list</div>}
    </Repeat>
  );
}

Booleans, Null, and Undefined Are Ignored

false, null, undefined, and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

如何传递多个slots

从上面可以看出React中slot其实就是prop,所以我们需要传递多个slot时,就使用prop的形式传递即可

<MyDialog 
    left={<div>left</div>}>
    <div>----</div>
</MyDialog>
                            // 使用
<div>
    <div className="left">left{this.props.left}</div>
    {this.props.children}
</div>