【发布时间】:2018-04-17 09:23:17
【问题描述】:
我在使用带有来自 React Bootstrap 的复选框的 Nav 和 NavItem 时遇到了一个特殊的问题。问题是,如果我直接单击复选框而不是 NavItem 按钮,复选框将不会正确重新呈现,但我的状态已更新。
示例:给定下面的代码,我渲染组件并直接单击复选框。在这种情况下,showMap 将设置为 false,因为我们在构造函数中将其设置为 true,但在 html 视图中仍会选中复选框。但是,如果我单击 NavItem 而不是直接单击复选框,则状态 showMap 和视图都会正确更新。
https://react-bootstrap.github.io/components.html#navs
import * as React from "react";
import * as ReactDOM from "react-dom";
import { LinkContainer } from 'react-router-bootstrap';
import { Col, Nav, NavItem, Checkbox } from "react-bootstrap";
interface IProps {
}
interface IState {
showMap: boolean
}
export class Menu extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
showMap: true
}
}
toggleCheckbox = (event: any) => {
event.preventDefault();
this.setState({ showMap: !this.state.showMap });
}
render() {
return (
<div>
<Nav bsStyle="tabs" activeKey="1">
<LinkContainer to="/test">
<NavItem eventKey="1">Test</NavItem>
</LinkContainer>
<LinkContainer to="/test2">
<NavItem eventKey="2">Test2</NavItem>
</LinkContainer>
<NavItem eventKey="3" onClick={this.toggleCheckbox}><Checkbox name="showMap" inline checked={this.state.showMap} readOnly >
Show Map </Checkbox></NavItem>
</Nav>
</div>
)
}
}
更新:
也这样试了,结果还是一样:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { LinkContainer } from 'react-router-bootstrap';
import { Navbar, Nav, NavItem, Checkbox } from "react-bootstrap";
interface IProps {
}
interface IState {
showMap: boolean
}
export class Menu extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
showMap: true
}
}
toggleCheckbox = (event: any) => {
event.preventDefault();
this.setState({ showMap: !this.state.showMap });
}
render() {
return (
<div>
<Navbar>
<Nav bsStyle="tabs" activeKey="1">
<LinkContainer to="/test">
<NavItem eventKey="1">Test</NavItem>
</LinkContainer>
<LinkContainer to="/test2">
<NavItem eventKey="2">Test2</NavItem>
</LinkContainer>
<NavItem eventKey="5" onClick={this.toggleCheckbox}><input type="checkbox" name="showMap"
checked={this.state.showMap} readOnly />Show map</NavItem>
</Nav>
</Navbar>
</div>
)
}
}
【问题讨论】:
-
这可能是因为您没有将 Nav 和 NavItem 组件包含在 react-bootstraps 的 Navbar 组件中。可能值得重构您的代码以使用 NavBar 的 onSelect 处理程序。
-
还在看这个,但它看起来像是 Checkbox 组件的问题。我在这里查看codesandbox.io/s/3r63j11pzm
-
@BenSmith 实现了导航栏但仍然没有运气,如果我调试代码,我可以看到 onClick 被点击并且复选框在视图中看起来不错。然而,在我的 onClick 代码运行后,它被重置为看起来没有任何变化但状态已更新。即使我正在运行
event.preventDefault();也会发生这种情况。 -
@GarryTaylor 尝试使用
<input type="checkbox" name="showMap" checked={this.state.showMap} readOnly />,但行为相同。 -
我也玩过 @GarryTaylor 不错的代码和框示例,它看起来确实是 react-bootstrap 库的问题。
标签: javascript twitter-bootstrap reactjs typescript react-bootstrap