在 React 16 中映射到片段
Map over Fragment in React 16
我正在尝试映射片段的子项,而片段又是组件的子项。例如:
const Frag = () => (
<React.Fragment key="test-key">
<div>test1</div>
<div>test2</div>
</React.Fragment>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => (
<a>
{child}
</a>
))
}
</div>
);
// Usage
<Outer>
<Frag />
</Outer>
这将导致单个 a
标记,即使该片段内部有多个 div。文档 (https://reactjs.org/docs/react-api.html#reactchildrenmap) seem to indicate that this should work with a keyed fragment and I think I am creating a keyed fragment correctly (https://reactjs.org/docs/fragments.html#keyed-fragments)。如有任何帮助,我们将不胜感激!
是的,但据我所知 - 您正在迭代 Outer
children。
尝试
React.Children.map(children[0].props.children, (child) => (
但是,仔细查看您的链接 - 我发现文档在这里说错了
the function will never be passed the container objects
这里有一个例子,清楚地表明容器被传递给了函数:
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
<div id="root" />
<script type="text/babel">
const Frag = () => (
<>
<div>test1</div>
<div>test2</div>
</>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => console.log(`Child type is ${child.type.name || child.type.toString()}`) || (
<a>
{child}
</a> ))
}
</div>
);
ReactDOM.render((
<div>
<Outer>
<>
<div>test1</div>
<div>test2</div>
</>
</Outer>
<Outer>
<Frag />
</Outer>
</div>
), document.getElementById('root'));
</script>
我正在尝试映射片段的子项,而片段又是组件的子项。例如:
const Frag = () => (
<React.Fragment key="test-key">
<div>test1</div>
<div>test2</div>
</React.Fragment>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => (
<a>
{child}
</a>
))
}
</div>
);
// Usage
<Outer>
<Frag />
</Outer>
这将导致单个 a
标记,即使该片段内部有多个 div。文档 (https://reactjs.org/docs/react-api.html#reactchildrenmap) seem to indicate that this should work with a keyed fragment and I think I am creating a keyed fragment correctly (https://reactjs.org/docs/fragments.html#keyed-fragments)。如有任何帮助,我们将不胜感激!
是的,但据我所知 - 您正在迭代 Outer
children。
尝试
React.Children.map(children[0].props.children, (child) => (
但是,仔细查看您的链接 - 我发现文档在这里说错了
the function will never be passed the container objects
这里有一个例子,清楚地表明容器被传递给了函数:
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
<div id="root" />
<script type="text/babel">
const Frag = () => (
<>
<div>test1</div>
<div>test2</div>
</>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => console.log(`Child type is ${child.type.name || child.type.toString()}`) || (
<a>
{child}
</a> ))
}
</div>
);
ReactDOM.render((
<div>
<Outer>
<>
<div>test1</div>
<div>test2</div>
</>
</Outer>
<Outer>
<Frag />
</Outer>
</div>
), document.getElementById('root'));
</script>