简单的FormCheck对我很有效:
<FormCheck
id="switchEnabled"
type="switch"
checked={this.state.settings.enabled}
onChange={this.toggleEnabled}
label="Enable"
/>
关键点是提供id。另一个重要的事情(为了加载初始值)是使用checked属性。
很遗憾,该交换机的文档并不是最好的。但以下内容应该能帮助你设置交换机以供使用。
const [isSwitchOn, setIsSwitchOn] = useState(false);
const onSwitchAction = () => {
setIsSwitchOn(!isSwitchOn);
};
...
<Form>
<Form.Switch
onChange={onSwitchAction}
id="custom-switch"
label="anything you want to put here"
checked={isSwitchOn}
disabled // apply if you want the switch disabled
/>
</Form>
...
custom
属性,它将显示开关按钮,但我仍然无法切换开关...<Form>
<Form.Check
custom
type="switch"
id="custom-switch"
label="Check this switch"
/>
</Form>
最初的回答。
import React from "react";
import ReactDOM from "react-dom";
import { Container, Form, FormCheck, Button } from "react-bootstrap";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
const [swt, setSwt] = React.useState(true);
const [swt2, setSwt2] = React.useState(true);
return (
<Container className="App">
Aprroch 1
<FormCheck custom type="switch">
<FormCheck.Input isInvalid checked={swt} />
<FormCheck.Label onClick={() => setSwt(!swt)}>
{`Value is ${swt}`}
</FormCheck.Label>
</FormCheck>
Approch 2
<Form.Check custom type="switch">
<Form.Check.Input isInvalid checked={swt2} />
<Form.Check.Label onClick={() => setSwt2(!swt2)}>
{`Value is ${swt2}`}
</Form.Check.Label>
</Form.Check>
</Container>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<FormCheck
id="switchEnabled1"
type="switch"
checked={this.state.settings.enabled}
onChange={this.toggleEnabled}
label="Enable"
/>
将开关的ID从switchEnabled更改为switchEnabled1似乎有效。如果您在多个位置使用它,则必须具有不同的ID。
我使用了像简单的Bootstrap这样的类
<div className="form-check form-switch">
<input className="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
<label className="form-check-label" for="flexSwitchCheckDefault">
switch checkbox input
</label>
</div>
我觉得我们需要像这样使用useState
<Form.Check
type="switch"
id="custom-switch"
label="Email"
checked={emailChecked}
onChange = {() => setEmailChecked(!emailChecked)}
style={{ marginLeft: '20px' }}
/>