react-bootstrap 组件开关不工作

Mo.*_*Mo. 9 javascript twitter-bootstrap reactjs react-bootstrap bootstrap-4

引导程序switches似乎不起作用。即使是文档版本也不起作用

<Form>
  <Form.Check 
    type="switch"
    id="custom-switch"
    label="Check this switch"
  />
  <Form.Check 
    disabled
    type="switch"
    label="disabled switch"
    id="disabled-custom-switch"
  />
</Form>
Run Code Online (Sandbox Code Playgroud)

编辑anger-kepler-5wqi3

小智 10

简单的 FormCheck 对我有用:

<FormCheck 
  id="switchEnabled"
  type="switch"
  checked={this.state.settings.enabled}
  onChange={this.toggleEnabled}
  label="Enable"
/>
Run Code Online (Sandbox Code Playgroud)

关键是提供id。另一个重要的事情(加载初始值)是使用检查属性。


Mix*_*ike 7

不幸的是,该开关的文档并不是最好的。不过,以下内容应该有助于设置您使用的交换机。

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>
...
Run Code Online (Sandbox Code Playgroud)


Rah*_*hul 2

我找到了一种方法。

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);
Run Code Online (Sandbox Code Playgroud)

代码沙箱