首页 > 解决方案 > How can I pass data to a component without props in React?

问题描述

in the question I mean this. Imagine that I want to show a component Called "Form" and inside of "Form" there is a list of components called "checkboxex"

The normal way to do that is something like this:

const checkboxes = [1, 2, 3];
<Form checkBoxes={checkboxex} />

and then inside Form I just map that (Array.map)

I want to know is there is a way to do this:

const checkboxes = [1, 2, 3];

<Form>
   checkboxes.map(id =>
    <Checkbox key={id} id={id}/>
</Form>

Can anyone explain me if it is possible and what's the difference ? Thanks a lot !

标签: javascriptreactjscomponents

解决方案


您提到的模式是childrenprop 模式,其中嵌套JSX作为子元素传递给组件。

当您JS作为 的一部分包含时JSX,您必须将它们包装在{}

<Form>
  { checkboxes.map(id => <Checkbox key={id} id={id} />) }
</Form>

您的Form组件render方法看起来像这样。

render() {
  <div>
    {this.props.children}
  </div>
}

如果您传递的孩子是一个函数,您只需在Form组件中调用它。

<Form>
  {() => {
    return checkboxes.map(id => <Checkbox key={id} id={id} />)
  }}
</Form>

您只需调用子项,因为它是作为函数传递的。

render() {
      <div>
        {this.props.children()}
      </div>
    }

推荐阅读