在React中使用儿童

54 阅读1分钟

你可以在React中使用props.children,以便访问和利用你在创建组件实例时放在打开和关闭标签中的内容。

例如,如果我有一个Button组件,我可以像这样创建一个实例:<Button>HI!<Button> ,然后在Button组件里面,我可以用props.children访问这个文本。你也可以用它来创建包裹其他组件的组件--比如说<Container><Button /></Container>

function Button (props) {
  return <button>{props.children}</button>
}

然后我可以用<Button>Click Me!</Button> 来实例化这个组件,然后一个带有 "点击我 "文字的按钮将显示在页面上。

对于一个布局,我可以做这样的事情。

function Container ({ children }) {
  return <div style={{ maxWidth: 800px, margin: 0 auto }}>{children}</div>
}

注意:在这个例子中,我对props对象进行了重组,所以我可以直接使用children。

然后为了实例化它,我可以这样做。

<Container>
  <h1>Welcome to my App</h1>
  <p>Hello, hi, this is my paragraph</p>
</Container>

通常,为了将道具从一个组件传递到另一个组件,你需要做<Button label="hello" /> ,然后在组件中使用props.label ,但React children更灵活,允许你在JSX中更紧密地反映HTML。