Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何选择React中的所有复选框?_Javascript_Reactjs_Meteor_Checkbox - Fatal编程技术网

Javascript 如何选择React中的所有复选框?

Javascript 如何选择React中的所有复选框?,javascript,reactjs,meteor,checkbox,Javascript,Reactjs,Meteor,Checkbox,我有这个模块: import React, { Component } from 'react' import EmailListItem from './EmailListItem' import { createContainer } from 'meteor/react-meteor-data' import { Emails } from '../../../../../imports/collections/emails/Emails' class EmailList extends

我有这个模块:

import React, { Component } from 'react'
import EmailListItem from './EmailListItem'
import { createContainer } from 'meteor/react-meteor-data'
import { Emails } from '../../../../../imports/collections/emails/Emails'

class EmailList extends Component {
  constructor (props) {
    super(props)
    this.state = {
      selectedEmails: new Set(),
      checked: false
    }
  }

  handleSelectedEmails (selectedEmail, checked) {
    let selectedEmails = this.state.selectedEmails
    if (checked) {
      selectedEmails.add(selectedEmail)
    } else {
      selectedEmails.delete(selectedEmail)
    }
    this.setState({selectedEmails})
    console.log('selectedEmails', this.state.selectedEmails)
  }
  removeSelected () {
    const selectedEmails = Array.from(this.state.selectedEmails)
    Meteor.call('emails.remove', selectedEmails, (err, result) => {
      if (err) console.log(err)
      if (result) console.log(result)
    })
  }
  checkedClick () {
    this.setState({checked: !this.state.checked})
    console.log('chcekedClick')
  }
  renderList () {
    console.log(this.props)
    return this.props.emails.map(email => {
      console.log(email)
      const { name, opr, ctr, _id } = email
      const createdAt = email.createdAt.toDateString()
      const link = `/dashboard/emailpreview/${_id}`
      return (
        <EmailListItem
          selecetedAllEmails={this.state.checked}
          handleSelectedEmails={this.handleSelectedEmails.bind(this)}
          name={name}
          createdAt={createdAt}
          opr={opr}
          ctr={ctr}
          link={link}
          key={email._id}
          id={email._id} />
        )
    })
  }
  render () {
    // TODO: make checks with state
    return (
      <div className="email_list">
        <table>
          <thead>
            <tr>
              <td><input onChange={this.checkedClick.bind(this)} type="checkbox" checked={this.state.checked} /></td>
              <td>Title<button onClick={this.removeSelected.bind(this)} className="btn btn-danger">Remove</button></td>
              <td>Dates</td>
              <td>Open Rates</td>
              <td>CTA</td>
            </tr>
          </thead>
          <tbody>
            {this.renderList()}
          </tbody>
        </table>

      </div>
  )
  }
}

export default createContainer(() => {
  Meteor.subscribe('emails')
  return { emails: Emails.find({}).fetch() }
}, EmailList)
import React,{Component}来自“React”
从“./EmailListItem”导入EmailListItem
从“meteor/react meteor数据”导入{createContainer}
从“../../../../../imports/collections/Emails/Emails”导入{Emails}
类EmailList扩展组件{
建造师(道具){
超级(道具)
此.state={
selectedEmails:new Set(),
勾选:假
}
}
可处理的选定邮件(选定邮件,选中){
让selectedEmails=this.state.selectedEmails
如果(选中){
选择电子邮件。添加(选择电子邮件)
}否则{
selectedEmail.delete(selectedEmail)
}
this.setState({selectedEmails})
console.log('selectedEmails',this.state.selectedEmails)
}
removeSelected(){
const selectedEmails=Array.from(this.state.selectedEmails)
Meteor.call('emails.remove',selectedEmails,(err,result)=>{
if(err)console.log(err)
if(结果)console.log(结果)
})
}
选中单击(){
this.setState({checked:!this.state.checked})
console.log('chcekedClick')
}
渲染列表(){
console.log(this.props)
返回此.props.emails.map(电子邮件=>{
控制台日志(电子邮件)
const{name,opr,ctr,_id}=email
const createdAt=email.createdAt.toDateString()
const link=`/dashboard/emailpreview/${u id}`
返回(
)
})
}
渲染(){
//待办事项:与州政府核实
返回(
标题记忆
日期
未平仓价
CTA
{this.renderList()}
)
}
}
导出默认createContainer(()=>{
Meteor.subscribe(“电子邮件”)
返回{emails:emails.find({}).fetch()}
},电邮名单)
它呈现了这个模块

import React, { Component } from 'react'
import { Link } from 'react-router'

class EmailListItem extends Component {
  constructor (props) {
    super(props)
    this.state = {
      checked: false
    }
  }

  checkedClick () {
    this.setState({checked: !this.state.checked})
    console.log('chcekedClick')
  }

  componentDidUpdate () {
    console.log('componentDidUpdate')
    const { myCheckbox } = this.refs
    console.log('myCheckbox', myCheckbox)
    console.log('myCheckbox.name', myCheckbox.name)
    console.log('myCheckbox.checked', myCheckbox.checked)
    if (this.props.selecetedAllEmails) {
      console.log('componentDidUpdate IF')
      this.checkedClick()
      this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
    }
  }
  render () {
    console.log('_id', this.props.id)
    return (
      <tr>
        <td><input ref="myCheckbox"
          onChange={(event) => {
            this.checkedClick()
            this.props.handleSelectedEmails(event.target.name, event.target.checked)
          }}
          checked={this.state.checked}
          type="checkbox" name={this.props.id} /></td>
        <td><Link to={this.props.link}>{this.props.name}</Link></td>
        <td>{this.props.createdAt}</td>
        <td>Open Rates</td>
        <td>CTA</td>
      </tr>
    )
  }
}

export default EmailListItem
import React,{Component}来自“React”
从“反应路由器”导入{Link}
类EmailListItem扩展组件{
建造师(道具){
超级(道具)
此.state={
勾选:假
}
}
选中单击(){
this.setState({checked:!this.state.checked})
console.log('chcekedClick')
}
组件更新(){
console.log('componentDidUpdate')
const{myCheckbox}=this.refs
console.log('myCheckbox',myCheckbox)
console.log('myCheckbox.name',myCheckbox.name)
console.log('myCheckbox.checked',myCheckbox.checked)
if(this.props.selectedallemails){
console.log('componentDidUpdate IF')
这个。checkedClick()
this.props.handleSelectedEmails(myCheckbox.name,myCheckbox.checked)
}
}
渲染(){
console.log(“u id”,this.props.id)
返回(
{
这个。checkedClick()
this.props.handleSelectedEmails(event.target.name、event.target.checked)
}}
checked={this.state.checked}
type=“checkbox”name={this.props.id}/>
{this.props.name}
{this.props.createdAt}
未平仓价
CTA
)
}
}
导出默认EmailListItem

正如您所看到的,对于每个电子邮件项目,我都有一个复选框。我可以选择几个复选框,然后单击“删除”按钮,该按钮将调用“删除我所选的项目”。现在在顶部我有一个复选框,它应该选中所有的复选框。我的解决方案是存储选中的全局复选框,并将其作为道具传递给所有项目。然后在项目中,我对componentDidUpdate执行检查,如果选中了全局复选框,那么我也会检查该项目。但这会导致无限循环。这里最好的解决方案是什么?

您可以使用
组件WillReceiveProps
而不是
组件DidUpdate

class EmailListsItem extends Component {
  // ...
  componentWillReceiveProps (nextProps) {
    const { myCheckbox } = this.refs

    // if selecetedAllEmails is updated from false to true
    if (nextProps.selecetedAllEmails && !this.props.selecetedAllEmails) {
      this.checkedClick()
      this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
    }
  }
  // ...
}

我认为,不需要为每个电子邮件id维护单独的状态,您已经在
parent
组件中存储了值,在
props
中从
parent
传递值,另一件事是选择所有电子邮件id,您在parent中维护一个bool,在props中传递值时检查bool,如果布尔值为真,则通过
true
,否则检查
set
并通过
set
返回的结果

检查JSFIDLE的工作解决方案:

尝试此
renderList
方法:

renderList () {
 return this.props.emails.map(email => {
      const { name, opr, ctr, _id } = email
      const createdAt = email.createdAt.toDateString()
      const link = `/dashboard/emailpreview/${_id}`
      return (
        <EmailListItem
          handleSelectedEmails={this.handleSelectedEmails.bind(this)}
          name={name}
          createdAt={createdAt}
          opr={opr}
          ctr={ctr}
          link={link}
          key={email._id}
          id={email._id} 
          value={this.state.checked || this.state.selectedEmails.has(email._id)}
        />
      )
   })
 }
renderList(){
返回此.props.emails.map(电子邮件=>{
const{name,opr,ctr,_id}=email
const createdAt=email.createdAt.toDateString()
const link=`/dashboard/emailpreview/${u id}`
返回(
)
})
}
并使用此组件:

class EmailListItem extends Component {
  constructor (props) {
    super(props)
    //this.state = {
    //  checked: false
    //}
  }

  //checkedClick () {
  //  this.setState({checked: !this.state.checked})
  //  console.log('chcekedClick')
  //}

  //componentDidUpdate () {
  //  if (this.props.selecetedAllEmails) {
  //    this.checkedClick()
  //    this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
  //  }
  //}

  render () {
    return (
      <tr>
        <td><input ref="myCheckbox"
          onChange={(event) => {
            this.props.handleSelectedEmails(event.target.name, event.target.checked)
          }}
          checked={this.props.value}
          type="checkbox" name={this.props.id} /></td>
        <td><Link to={this.props.link}>{this.props.name}</Link></td>
        <td>{this.props.createdAt}</td>
        <td>Open Rates</td>
        <td>CTA</td>
      </tr>
    )
  }
}
类EmailListItem扩展组件{
建造师(道具){
超级(道具)
//此.state={
//勾选:假
//}
}
//选中单击(){
//this.setState({checked:!this.state.checked})
//console.log('chcekedClick')
//}
//组件更新(){
//if(this.props.selectedallemails){
//这个。checkedClick()
//this.props.handleSelectedEmails(myCheckbox.name,myCheckbox.checked)
//  }
//}
渲染(){
返回(
{
this.props.handleSelectedEmails(event.target.name、event.target.checked)
}}
选中={this.props.value}
type=“checkbox”name={this.props.id}/>
{this.props.name}
{this.props.createdAt}
未平仓价
CTA
)
}
}

如果对u不起作用,请告诉我。

虽然一些答案提供了选择所有复选框的特定功能,但我还需要一些常见功能,如取消选择全部、选择全部然后取消选择部分、手动选择所有选择框复选框时等等。。。所以我写了所有这些,并将其作为答案发布在这里。感谢所有回复的人。此代码基于Mayank Shuklas答案。请注意,它可能还不够完美,因为我还没有对它进行适当的测试,而且它肯定需要一些重构

import React, { Component } from 'react'
import EmailListItem from './EmailListItem'
import { createContainer } from 'meteor/react-meteor-data'
import { Emails } from '../../../../../imports/collections/emails/Emails'

class EmailList extends Component {
  constructor (props) {
    super(props)
    this.state = {
      selectedEmails: new Set(),
      checked: false
    }
  }

  handleSelectedEmails (allSelected, individualSelected, selectedEmail, checked) {
    console.log('allSelected', allSelected)
    console.log('individualSelected', individualSelected)
    console.log('selectedEmail', selectedEmail)
    console.log('checked', checked)
    let selectedEmails = this.state.selectedEmails
    if (allSelected && !individualSelected) {
        this.props.emails.forEach((email) => {
          selectedEmails.add(email._id)
        })
    } else if (!allSelected && !individualSelected) {
      selectedEmails.clear()
    } else if (individualSelected) {
      if (checked) {
        selectedEmails.add(selectedEmail)
        if (selectedEmails.size === this.props.emails.length) {
          this.checkAll()
        }
      } else {
        selectedEmails.delete(selectedEmail)
        this.setState({checked})
      }
    }
    this.setState({selectedEmails})
    console.log('selectedEmails', this.state.selectedEmails)
  }
  removeSelected () {
    const selectedEmails = Array.from(this.state.selectedEmails)
    Meteor.call('emails.remove', selectedEmails, (err, result) => {
      if (err) console.log(err)
      if (result) console.log(result)
    })
  }
  checkAll () {
    this.setState({checked: !this.state.checked})
    console.log('chcekedClick', this.state.checked)
    this.handleSelectedEmails(!this.state.checked, false)
  }
  renderList () {
    console.log(this.props)
    return this.props.emails.map(email => {
      // console.log(email)
      const { name, opr, ctr, _id } = email
      const createdAt = email.createdAt.toDateString()
      const link = `/dashboard/emailpreview/${_id}`
      return (
        <EmailListItem
          handleSelectedEmails={this.handleSelectedEmails.bind(this)}
          name={name}
          createdAt={createdAt}
          opr={opr}
          ctr={ctr}
          link={link}
          key={email._id}
          id={email._id}
          value={this.state.checked || this.state.selectedEmails.has(email._id)} />
        )
    })
  }
  render () {
    // TODO: make checks with state
    return (
      <div className="email_list">
        <table>
          <thead>
            <tr>
              <td><input onChange={this.checkAll.bind(this)} type="checkbox" checked={this.state.checked} /></td>
              <td>Title<button onClick={this.removeSelected.bind(this)} className="btn btn-danger">Remove</button></td>
              <td>Dates</td>
              <td>Open Rates</td>
              <td>CTA</td>
            </tr>
          </thead>
          <tbody>
            {this.renderList()}
          </tbody>
        </table>

      </div>
  )
  }
}

export default createContainer(() => {
  Meteor.subscribe('emails')
  return { emails: Emails.find({}).fetch() }
}, EmailList)
import React, { Component } from 'react'
import { Link } from 'react-router'

class EmailListItem extends Component {
  render () {
    console.log('_id', this.props.id)
    return (
      <tr>
        <td><input ref="myCheckbox"
          onChange={(event) => {
            this.props.handleSelectedEmails(false, true, event.target.name, event.target.checked)
          }}
          checked={this.props.value}
          type="checkbox" name={this.props.id} /></td>
        <td><Link to={this.props.link}>{this.props.name}</Link></td>
        <td>{this.props.createdAt}</td>
        <td>Open Rates</td>
        <td>CTA</td>
      </tr>
    )
  }
}

export default EmailListItem