[英]React - Map Over Array Of Components To Return
Im trying to dynamically print a lot of components into a li
list. 我试图将许多组件动态打印到一个
li
列表中。
In the parent component, the list menuLinks
is an array. 在父组件中,列表
menuLinks
是一个数组。 Each child of menuLinks
is a component (LinkToChangePassword is a react functional component): menuLinks
每个子menuLinks
都是一个组件(LinkToChangePassword是一个react功能组件):
export default class Header extends Component{
constructor(props){
super( props );
}
render(){
const menuLinks = [
LinkToChangePassword,
LinkToResetPassword,
LinkToChangeEmail,
LinkToLogOut
];
return(
<div className="header">
<LinkToHome classAttr=""/>
<h1 className="">{ this.props.heading }</h1>
<DropDownMenu links = { menuLinks }/>
</div>
);
}
}
In my child component, I'd like to attach these components: 在我的子组件中,我想附加以下组件:
export default class DropDownMenu extends Component{
constructor( props ){
super( props );
}
render(){
let renderMenuItems = this.props.links.map(
( item, i ) => <li className = "menuItem"
key = {`li${i}`}>
{item}
</li>
);
return <ul className = "profileMenu">
{ renderMenuItems }
</ul>;
}
}
However, this doesnt work & I get empty list. 但是,这不起作用&我得到空列表。
Your trying to reference a react component by name only in JSX without surrounding it with angled brackets: 您试图仅在JSX中按名称引用react组件, 而没有用尖括号将其包围:
ComponentNameHere instead of: <ComponentNameHere> ComponentNameHere而不是: <ComponentNameHere>
One solution: 一种解决方案:
You'll need to ensure you are importing you components into you DropDownMenu class. 您需要确保将组件导入到DropDownMenu类中。
You can then replace {item} statement within your .map call to use React.createElement() 然后,您可以在.map调用中替换{item}语句以使用React.createElement()
{React.createElement(item, null)}
Amended render function: 修改了渲染功能:
render(){
let renderMenuItems = this.props.links.map( ( item, i ) =>
<li className = "menuItem" key = {`li${i}`}>
{React.createElement(item, null)}
</li>
);
return <ul className = "profileMenu"> { renderMenuItems } </ul>;
}
Try this once. 尝试一次。 Maybe this can help.
也许可以帮上忙。
const menuLinks = [
<LinkToChangePassword />,
<LinkToResetPassword />,
<LinkToChangeEmail />,
<LinkToLogOut />
];
Here is a fiddle https://jsfiddle.net/jwm6k66c/1785/ 这是一个小提琴https://jsfiddle.net/jwm6k66c/1785/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.