Javascript 如何从 react-bootstrap 复选框获取值/属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42682406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:21:30  来源:igfitidea点击:

How to get values/properties from a react-bootstrap checkbox?

javascriptreactjscheckboxreduxreact-bootstrap

提问by John Meyer

I'm trying to use the react-bootstrap checkbox (https://react-bootstrap.github.io/components.html#forms-controls) and I need to fire an event when it changes state. It would also be great to be able to programatically un/check it and/or tell if it is checked. Unfortunately when the code is transpiled and rendered it wraps the input in a div.

我正在尝试使用 react-bootstrap 复选框(https://react-bootstrap.github.io/components.html#forms-controls),我需要在它更改状态时触发一个事件。能够以编程方式取消/检查它和/或判断它是否被检查也很棒。不幸的是,当代码被转译和呈现时,它会将输入包装在一个 div 中。

How can I find this in the dom and manipulate it?

我怎样才能在dom中找到它并操纵它?

My code looks similar to this:

我的代码看起来类似于:

import React, { PropTypes } from 'react';
import { Checkbox } from 'react-bootstrap';

const EditItem = (props) => {

  return (
    <div>
      <Checkbox style={{ marginLeft: '15px' }} >{props.itemLable}</Checkbox>
    </div>
  );
};

export default EditItem;

And the browser renders this:

浏览器呈现这个:

...
<div class="checkbox" style="margin-left: 15px;">
  <label>
    <input type="checkbox">
  </label>
</div>
...

I see the inputRef prop in the documentation but I can't find any examples of this or get it to work myself.

我在文档中看到 inputRef 道具,但我找不到任何示例或让它自己工作。

回答by Jordan Running

There are two ways: The React way and the not-so-React way.

有两种方式:React 方式和非 React 方式。

The React way is to set the child component's state by passing it props and respond to changes in its state by attaching event handlers. In the case of Checkbox, that means setting the checkedand onChangeprops.

React 的方式是通过传递 props 来设置子组件的状态,并通过附加事件处理程序来响应其状态的变化。在 Checkbox 的情况下,这意味着设置checkedonChange道具。

Note in the below example how the parent component (App) keeps track of the Checkbox's state and can both set it with this.setStateand query it with this.state.checkboxChecked.

请注意在下面的示例中父组件(应用程序)如何跟踪复选框的状态,并且可以this.setState使用this.state.checkboxChecked.

const { Checkbox, Button } = ReactBootstrap;

class App extends React.Component {
  constructor() {
    super();
    this.state = { checkboxChecked: false };
    this.handleChange = this.handleChange.bind(this);
    this.handleIsItChecked = this.handleIsItChecked.bind(this);
    this.handleToggle = this.handleToggle.bind(this);
  }
  
  render() {
    return (
      <div>
        <Checkbox
          checked={this.state.checkboxChecked}
          onChange={this.handleChange} />
        <Button type="button" onClick={this.handleToggle}>Toggle</Button>
        <Button type="button" onClick={this.handleIsItChecked}>Is it checked?</Button>
      </div>
    );
  }
  
  handleChange(evt) {
    this.setState({ checkboxChecked: evt.target.checked });
  }
  
  handleIsItChecked() {
    console.log(this.state.checkboxChecked ? 'Yes' : 'No');
  }
  
  handleToggle() {
    this.setState({ checkboxChecked: !this.state.checkboxChecked });
  }
}

ReactDOM.render(<App/>, document.querySelector('div'));
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.30.8/react-bootstrap.min.js"></script>
<div></div>

The not-so-React way is to get a reference to the rendered DOM element and access its checkedproperty directly. I don't recommend this, because it necessarily pollutes your lovely functional React code with icky imperative code. Nevertheless, with React-Bootstrap you can do it by setting the inputRefprop, as in the below example:

不那么 React 的方法是获取对呈现的 DOM 元素的引用并checked直接访问其属性。我不推荐这样做,因为它必然会用令人讨厌的命令式代码污染你可爱的函数式 React 代码。不过,使用 React-Bootstrap,您可以通过设置inputRefprop 来实现,如下例所示:

const { Checkbox, Button } = ReactBootstrap;

class App extends React.Component {
  constructor() {
    super();
    this.handleIsItChecked = this.handleIsItChecked.bind(this);
    this.handleToggle = this.handleToggle.bind(this);
  }
  
  render() {
    return (
      <div>
        <Checkbox
          onChange={this.handleChange}
          inputRef={ref => this.myCheckbox = ref} />
        <Button type="button" onClick={this.handleToggle}>Toggle</Button>
        <Button type="button" onClick={this.handleIsItChecked}>Is it checked?</Button>
      </div>
    );
  }
  
  handleIsItChecked() {
    console.log(this.myCheckbox.checked ? 'Yes' : 'No');
  }
  
  handleToggle() {
    this.myCheckbox.checked = !this.myCheckbox.checked;
  }
}

ReactDOM.render(<App/>, document.querySelector('div'));
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.30.8/react-bootstrap.min.js"></script>
<div></div>

回答by Udugam

Thanks for the above answers. I generalized the above slightly for use when you have more than one checkbox in a given component:

感谢以上的回答。当给定组件中有多个复选框时,我稍微概括了上述内容:

  constructor() {
    super();
    this.state = { YourInputName: false };
    this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
  }

  render() {
    return (
      <div>
        <Checkbox
          name="YourInputName"
          onChange={this.handleCheckboxChange} />
      </div>
    );
  }

  handleCheckboxChange(event) {
    const target = event.target
    const checked = target.checked
    const name = target.name
    this.setState({
        [name]: checked,
    });
  }

回答by ohiock

Have you tried setting an onChange property to your checkbox?

您是否尝试过为复选框设置 onChange 属性?

handleChange(event) {
    this.setState(*set checkbox state here*);
}

<Checkbox onChange={this.handleChange}></Checkbox>