Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.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中下拉列表中的Multiselect_Javascript_Reactjs_Checkbox_Dropdown_Bootstrap Multiselect - Fatal编程技术网

Javascript React中下拉列表中的Multiselect

Javascript React中下拉列表中的Multiselect,javascript,reactjs,checkbox,dropdown,bootstrap-multiselect,Javascript,Reactjs,Checkbox,Dropdown,Bootstrap Multiselect,我正在尝试从我创建的下拉列表中选择多个不同的值。下面的代码实际上显示了这些人的名字,但我希望能够选择多个 名字 {this.state.names.map((name)=>{name.display})} 这类似于设置单个值,但该值是数组,而不是字符串或数字 首先,您必须更改value和onChange函数的作用。对于值,将默认状态设置为数组。对于onChange,我们将对其进行设置,无论何时选中该项,它都会设置一个新状态,如下所示: javascript state = { selecte

我正在尝试从我创建的下拉列表中选择多个不同的值。下面的代码实际上显示了这些人的名字,但我希望能够选择多个


名字
{this.state.names.map((name)=>{name.display})}

这类似于设置单个值,但该值是数组,而不是字符串或数字

首先,您必须更改value和onChange函数的作用。对于值,将默认状态设置为数组。对于
onChange
,我们将对其进行设置,无论何时选中该项,它都会设置一个新状态,如下所示:

javascript

state = {
 selectedNames:[]
}

onChange = (e) => {
  e.preventDefault()
  this.setState(prevState => ({selectedNames: [...prevState.selectedNames, e.target.value]})
}
希望这有帮助

(我假设您正在使用
react引导程序

答复 您需要将另一个道具传递到
表单.控件
,以指定希望您的选择允许多个选择。您可以使用
multiple={true}
或缩写
multiple
(两者都是等效的)

在他们的文档中使用multiselect,这可能会有所帮助

我把这些放在一起,也许可以说明如何使用它

有什么棘手的 使用react处理状态可能很困难。表单是出了名的具有挑战性,因为它们涉及很多内部状态

其他需要尝试的事情
  • 使用react钩子来管理状态,而不是类组件。在我看来,这可以使与国家合作更加容易
我的例子中的Bug
  • 当只有一个选择并且您尝试取消选择时,不会触发
    onChange
    事件。我不知道为什么会发生这种事

事件需要添加到单个选项中,多选需要相当多的行来实现。这里有一些片段,只针对您可能关心的部分。正如你所看到的,我没有使用任何第三方控件

      <div className="_action">
        <span
          role="button"
          aria-pressed="false"
          tabIndex={0}
          onClick={() => { onClear() }}
        >
          Clear Selection
        </span>
      </div>
      {options.map(option => (
        <div
          role="presentation"
          className="_item"
          key={option.value}
          onClick={() => { onSelect(option.value) }}
        >
          <Checkbox value={isChecked(option, value)} />
          <span className="_label">{option.label}</span>
        </div>
      ))}
以及一个实用功能
切换ValueIINoOptions

const toggleValueInOptions = (value, key, options) => {
  if (!value) return []

  const values = value.slice()
  const index = values.indexOf(key)
  if (index >= 0) {
    values.splice(index, 1)
  } else {
    values.push(key)
  }

  if (!options) return values

  return options.reduce((acc, option) => {
    if (values.includes(option.value)) {
      acc.push(option.value)
    }
    return acc
  }, [])
}

export default toggleValueInOptions
============== 供您参考,这是父级
MultiSelect
的完整代码

import React, { useState, useCallback, useRef } from 'react'
import PropTypes from 'prop-types'
import { useClickOutside } from '../../utils'
import InputBase from '../InputBase'
import Pills from './Pills'
import MultiSelection from './MultiSelection'
import MultiSelectStyle from './MultiSelectStyle'
import SelectIcon from './SelectIcon'
import { optionsType, valuesType } from './optionsType'
import toggleValueInOptions from './toggleValueInOptions'
import valueToItems from './valueToItems'
import SelectionSummary from './SelectionSummary'

/**
 * @memberof MultiSelect
 * @param {Object} _                Props
 * @param {elementType} _.Style       Style component
 * @param {string} _.name             Input name
 * @param {valueType[]} _.value         Input value of array
 * @param {func} _.onChange           Value change event
 * @param {optionsType[]} _.options     Options array
 * @param {elementType} _.Selection=MultiSelection    Component for dropdown selection
 * @param {bool} _.disabled=false     Input disabled flag
 * @param {bool} _.width=auto         Input width
 * @param {string} _.placeholder      Input placeholder
 * @param {elementType} _.DropdownIcon=DropdownIcon   Compoent for dropdown icon component
 * @param {number} _.pillVisibleMax   Max pill displayed
 * @param {elementType} _.Summary=SelectionSummary    Component for dropdown summary
 */
const MultiSelect = ({
  Style, name, value, options, onChange,
  Selection, disabled, width, placeholder,
  DropdownIcon, pillVisibleMax, Summary,
  ...props
}) => {
  const [focus, setFocus] = useState(false)

  const onExpand = useCallback(() => {
    if (!disabled) setFocus(true)
  }, [disabled])
  const onCollapse = useCallback(() => { setFocus(false) }, [])
  const ref = useRef()
  useClickOutside({ ref, handler: () => { onCollapse() } })

  const onSelect = useCallback(v => {
    const e = {
      target: {
        name,
        value: toggleValueInOptions(value, v, options)
      }
    }
    onChange(e)
  }, [name, value, options, onChange])

  const onClear = useCallback(() => {
    const e = { target: { name, value: [] } }
    onChange(e)
  }, [name, onChange])

  const after = <DropdownIcon focus={focus} onExpand={onExpand} onCollapse={onCollapse} />

  const phText = value.length ? '' : placeholder
  const vText = (value.length > pillVisibleMax) ? `${value.length} Selected` : ''

  return (
    <Style ref={ref}>
      <InputBase
        value={vText}
        placeholder={phText}
        disabled={disabled}
        readOnly
        after={after}
        onFocus={onExpand}
        width={width}
        {...props}
      />
      {!vText && (
        <Pills
          items={valueToItems(value, options)}
          onSelect={onSelect}
          disabled={disabled}
        />
      )}
      {focus && (
        <Selection
          value={value}
          options={options}
          onSelect={onSelect}
          onClear={onClear}
          Summary={Summary}
        />
      )}
    </Style>
  )
}

MultiSelect.propTypes = {
  Style: PropTypes.elementType,
  name: PropTypes.string,
  value: valuesType,
  options: optionsType,
  onChange: PropTypes.func,
  Selection: PropTypes.elementType,
  disabled: PropTypes.bool,
  width: PropTypes.string,
  placeholder: PropTypes.string,
  DropdownIcon: PropTypes.elementType,
  pillVisibleMax: PropTypes.number,
  Summary: PropTypes.elementType
}

MultiSelect.defaultProps = {
  Style: MultiSelectStyle,
  name: '',
  value: [],
  options: [],
  onChange: () => { },
  Selection: MultiSelection,
  disabled: false,
  width: '',
  placeholder: '',
  DropdownIcon: SelectIcon,
  pillVisibleMax: 99,
  Summary: SelectionSummary
}

export default MultiSelect
import React,{useState,useCallback,useRef}来自“React”
从“道具类型”导入道具类型
从“../../utils”导入{useClickOutside}
从“../InputBase”导入InputBase
从“./药片”导入药片
从“/MultiSelection”导入MultiSelection
从“./MultiSelectStyle”导入MultiSelectStyle
从“./SelectIcon”导入SelectIcon
从“/optionsType”导入{optionsType,valuesType}
从“./toggleValueInOptions”导入toggleValueInOptions
从“/valueToItems”导入valueToItems
从“/SelectionSummary”导入SelectionSummary
/**
*@memberofmultiselect
*@param{Object}Props
*@param{elementType}
*@param{string}\uName输入名称
*@param{valueType[]}\数组的值输入值
*@param{func}\ onChange值更改事件
*@param{optionsType[]}
*@param{elementType}389;.Selection=下拉选择的多重选择组件
*@param{bool}u2; disabled=错误输入禁用标志
*@param{bool}u2; width=自动输入宽度
*@param{string}\占位符输入占位符
*@param{elementType}
*@param{number}\显示pillVisibleMax最大药丸
*@param{elementType}\uux.Summary=选择下拉摘要的摘要组件
*/
常量多选=({
样式、名称、值、选项、onChange、,
选择、禁用、宽度、占位符、,
下拉图标、pillVisibleMax、摘要、,
…道具
}) => {
const[focus,setFocus]=useState(false)
const onExpand=useCallback(()=>{
如果(!禁用)设置焦点(true)
},[禁用])
const onCollapse=useCallback(()=>{setFocus(false)},[]))
const ref=useRef()
useClickOutside({ref,handler:()=>{onCollapse()}})
const onSelect=useCallback(v=>{
常数e={
目标:{
名称
值:切换值操作(值、v、选项)
}
}
onChange(e)
},[name,value,options,onChange])
const onClear=useCallback(()=>{
常量e={target:{name,value:[]}
onChange(e)
},[name,onChange])
常数后=
常量phText=value.length?'':占位符
const vText=(value.length>pillVisibleMax)?`${value.length}已选定`:“”
返回(
{!vText&&(
)}
{焦点&&(
)}
)
}
MultiSelect.propTypes={
样式:PropTypes.elementType,
名称:PropTypes.string,
value:valuesType,
选项:选项类型,
onChange:PropTypes.func,
选择:PropTypes.elementType,
禁用:PropTypes.bool,
宽度:PropTypes.string,
占位符:PropTypes.string,
下拉图标:PropTypes.elementType,
pillVisibleMax:PropTypes.number,
摘要:PropTypes.elementType
}
MultiSelect.defaultProps={
样式:多选样式,
名称:“”,
值:[],
选项:[],
onChange:()=>{},
选择:多选,
残疾人士:错,,
宽度:“”,
占位符:“”,
下拉图标:选择图标,
pillVisibleMax:99,
摘要:选择摘要
}
导出默认多重选择

您是否正在使用react引导?
import React, { useState, useCallback, useRef } from 'react'
import PropTypes from 'prop-types'
import { useClickOutside } from '../../utils'
import InputBase from '../InputBase'
import Pills from './Pills'
import MultiSelection from './MultiSelection'
import MultiSelectStyle from './MultiSelectStyle'
import SelectIcon from './SelectIcon'
import { optionsType, valuesType } from './optionsType'
import toggleValueInOptions from './toggleValueInOptions'
import valueToItems from './valueToItems'
import SelectionSummary from './SelectionSummary'

/**
 * @memberof MultiSelect
 * @param {Object} _                Props
 * @param {elementType} _.Style       Style component
 * @param {string} _.name             Input name
 * @param {valueType[]} _.value         Input value of array
 * @param {func} _.onChange           Value change event
 * @param {optionsType[]} _.options     Options array
 * @param {elementType} _.Selection=MultiSelection    Component for dropdown selection
 * @param {bool} _.disabled=false     Input disabled flag
 * @param {bool} _.width=auto         Input width
 * @param {string} _.placeholder      Input placeholder
 * @param {elementType} _.DropdownIcon=DropdownIcon   Compoent for dropdown icon component
 * @param {number} _.pillVisibleMax   Max pill displayed
 * @param {elementType} _.Summary=SelectionSummary    Component for dropdown summary
 */
const MultiSelect = ({
  Style, name, value, options, onChange,
  Selection, disabled, width, placeholder,
  DropdownIcon, pillVisibleMax, Summary,
  ...props
}) => {
  const [focus, setFocus] = useState(false)

  const onExpand = useCallback(() => {
    if (!disabled) setFocus(true)
  }, [disabled])
  const onCollapse = useCallback(() => { setFocus(false) }, [])
  const ref = useRef()
  useClickOutside({ ref, handler: () => { onCollapse() } })

  const onSelect = useCallback(v => {
    const e = {
      target: {
        name,
        value: toggleValueInOptions(value, v, options)
      }
    }
    onChange(e)
  }, [name, value, options, onChange])

  const onClear = useCallback(() => {
    const e = { target: { name, value: [] } }
    onChange(e)
  }, [name, onChange])

  const after = <DropdownIcon focus={focus} onExpand={onExpand} onCollapse={onCollapse} />

  const phText = value.length ? '' : placeholder
  const vText = (value.length > pillVisibleMax) ? `${value.length} Selected` : ''

  return (
    <Style ref={ref}>
      <InputBase
        value={vText}
        placeholder={phText}
        disabled={disabled}
        readOnly
        after={after}
        onFocus={onExpand}
        width={width}
        {...props}
      />
      {!vText && (
        <Pills
          items={valueToItems(value, options)}
          onSelect={onSelect}
          disabled={disabled}
        />
      )}
      {focus && (
        <Selection
          value={value}
          options={options}
          onSelect={onSelect}
          onClear={onClear}
          Summary={Summary}
        />
      )}
    </Style>
  )
}

MultiSelect.propTypes = {
  Style: PropTypes.elementType,
  name: PropTypes.string,
  value: valuesType,
  options: optionsType,
  onChange: PropTypes.func,
  Selection: PropTypes.elementType,
  disabled: PropTypes.bool,
  width: PropTypes.string,
  placeholder: PropTypes.string,
  DropdownIcon: PropTypes.elementType,
  pillVisibleMax: PropTypes.number,
  Summary: PropTypes.elementType
}

MultiSelect.defaultProps = {
  Style: MultiSelectStyle,
  name: '',
  value: [],
  options: [],
  onChange: () => { },
  Selection: MultiSelection,
  disabled: false,
  width: '',
  placeholder: '',
  DropdownIcon: SelectIcon,
  pillVisibleMax: 99,
  Summary: SelectionSummary
}

export default MultiSelect