控制react中的复选框

时间:2018-06-21 07:51:15

标签: javascript reactjs

我正在尝试在react中创建过滤器,在其中我操作网址以根据颜色,成本等向我退还产品

它可以正常工作,因此,如果您在网址中将?color=red更改为?color=white,它将在页面上显示不同的产品

它也可以正常工作,如果您在我的复选框过滤器组件中选择颜色,它将更新URL,然后显示新产品。也就是说,点击red会将网址从/sport更改为/sport?color=red,然后只向我返回带有红色的产品

但这是我的问题

如果我手动更改网址,则希望选中此复选框,以便尝试这样做:

checked={option.text === this.getParams() ? true : false}

这确实有效,但是随后我失去了实际选择和取消选择复选框的能力。有什么想法我可以做到的吗?我想同时使其成为受控和不受控制的组件?

2 个答案:

答案 0 :(得分:0)

您应该将复选框的状态设置为组件状态,然后在单击状态时更新该状态。您可以根据构造或安装的url设置初始状态。

类似这样的东西:

constructor(props) {
  super(props);

  const isChecked = this.props.match.params.checkbox === 'true';

  this.state = {
    checkbox: isChecked
  }
}

然后在您的复选框中:

<input type="checkbox" checked={this.state.checkbox} onChange={() => this._toggleCheckbox()} />

打开和关闭它的方法类似于:

toggleCheckbox() {
  this.setState({
    checkbox: !this.state.checkbox // will toggle to the opposite of the current state
  });
}

注意,该文件尚未经过测试,但已根据您提供的信息进行了编写。这背后的原理是您需要做的。最初在componentDidMount()而不是constructor()中设置复选框的状态也可能很有用,但这取决于您。复选框的onChange功能使用ES6,但是如果您愿意或不将ES6与this._toggleCheckbox().bind(this)

一起使用,则可以绑定该功能。

编辑

要在更改URL时更新复选框,而不是在单击时进行更新,可以更改切换方法以重定向浏览器,然后在componentWillReceiveProps中更新复选框。 从我自己的带有react-router的代码中获取,您可以使用'this.props.match.params'查找url参数。我使用react-router-dom包来更新URL。例如:

这将使您可以访问this.props.history

import { withRouter } from 'react-router-dom';

toggleCheckbox() {
  // Check the current state of the checkbox and update the url to the opposite
  let toCheck = this.props.match.params.checkbox === 'true' ? 'false' : 'checked';
  this.props.history.push('/?checkbox=' + toCheck);
}

componentWillReceiveProps(newProps) {
  // Check the new url and update the checkbox if it is different from the checkbox state
  if(newProps.match.params.checkbox != this.state.checkbox) {
    this.setState({checkbox: newProps.match.params.checkbox});
  }
}

答案 1 :(得分:0)

您需要将过滤器存储在state中。就像在构造函数中一样,您可以使用查询参数初始化状态,然后在复选框更改后更改状态。

您可以尝试类似的方法。您将需要根据您的用法更改此代码,这里我假设this.getParams('color')将返回所有选定颜色的数组。

构造函数状态初始化

constructor(props) {
  super(props);

  this.state = {
    filters: this.getParams('color') // consedering, it will return array
  }
}

默认选中复选框

defaultChecked ={this.state.filters.indexOf(option.text) === -1 ? false : true}
onChange={() => this.toggleCheckbox(option.text)}

用于切换

// if not present, then add it
// else remove it
toggleCheckbox(option) {
  if (this.state.filters.indexOf(option) === -1) {
    this.setState({
      filters: [...this.state.filters, option]
    })
  } else {
    this.setState({
      filters: this.state.filters.filter(text => text !== option)
    })
  }
}