javascript - 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 !
解决方案
您提到的模式是children
prop 模式,其中嵌套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>
}
推荐阅读
- homebrew - Cask 'thorn-writing' 定义是我没有安装的无效错误
- spring-boot - 如何将公共证书添加到谷歌存储桶
- angular - Angular 年份下拉列表
- mysql - ubuntu 如何将用户更改为“mysql”
- lua - (gLua) 真皮不工作。尝试调用方法“关闭”(零值)
- react-native - React 原生 Flat 列表优化
- mongodb - 用于日期比较的 mongodb 过滤器
- visual-studio-code - VSCode 无法将 SSH 连接到树莓派 4
- kubernetes - kubectl 执行 -it
获取 sh:无法打开“导出”:没有这样的文件或目录 - excel - excel vba - 硒查找元素