【发布时间】:2019-12-21 12:10:38
【问题描述】:
我一直在尝试在 react 中的自定义导航栏组件中呈现 react-bootstrap 组件。我设置了一个递归函数,它应该在反应渲染中运行并向下钻取,直到 NavDropDown 组件下没有导航项组件。目前,当任何向下钻取的尝试返回为未定义并且不显示在导航栏中时。
我尝试过以多种方式重新格式化我的 react 代码,包括/删除括号、切换到纯文本等。
代码如下:
navContent = {[
{
type : "link",
target: "/",
content: "Home"
},
{
type: "dropdown",
title: "CLICK ME",
content: [
{type : "item",
target: "/",
content: "home"
},
{type : "item",
target: "/",
content: "home"
}
]
},
{
type: "form",
formType: "text",
placeholder: "search",
className: "",
buttonType: "submit",
buttonContent: "Submit"
},
]}
export default class Navigation extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
getNavItem(navItem){
switch(navItem.type){
case 'link':
return <Nav.Link><Link to={navItem.target}>{navItem.content}</Link></Nav.Link>
case 'dropdown':
return <NavDropdown id="basic-nav-dropdown" title={navItem.title}>
{navItem.content.map(item => {this.getNavItem(item)})}
</NavDropdown>
case 'form':
return <Form inline> <FormControl type={navItem.formType} placeholder={navItem.placeholder} className={navItem.className}/><Button type={navItem.buttonType}>{navItem.buttonContent}</Button></Form>
case 'item':
return <NavDropdown.Item><Link to={navItem.target}>{navItem.content}</Link></NavDropdown.Item>
}
}
render(
){
return(
<Navbar bg="light" expand="lg">
<Link to="/"><Navbar.Brand>Home Placeholder</Navbar.Brand></Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
{this.props.navContent.map(navItem => this.getNavItem(navItem))}
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
理想情况下,当 case 开关点击 getNavItem 函数中的下拉列表时,它应该再次运行该函数,向下迭代到下拉对象的内容键,并在下拉列表下呈现其中的两个对象。目前下拉内容不呈现。
【问题讨论】:
-
是时候去“也许我写错了代码”了,所以不要带孩子开始。
<Nav>现在可以正确渲染了吗?如果没有,就可能出错的地方来调试代码并不是非常容易。它有效吗?酷:添加一个孩子,看看会发生什么
标签: javascript reactjs react-bootstrap