为什么使用reac-select渲染的Dropdown不能够使用原生事件触发?

React-Select 官网首页渲染了一个 Dropdown,
https://react-select.com/home

需要调用原声的事件出发列表下拉,
React-Select 源码:

<Control
  {...commonProps}
  innerRef={this.getControlRef}
  innerProps={{
    **onMouseDown: this.onControlMouseDown,**
    onTouchEnd: this.onControlTouchEnd,
  }}
  isDisabled={isDisabled}
  isFocused={isFocused}
  menuIsOpen={menuIsOpen}
>

但是现在不管在任何元素上面尝试

const event = new MouseEvent('mousedown', { view: window, cancelable: true, bubbles: true });
$0.dispatchEvent(event);

无法展开DropDown,请问是哪里出了错?

阅读 2.1k
2 个回答

React 事件17以前是在document上做的事件委托,17以后是在react根节点

import React, { useState } from 'react';

import Select from 'react-select';
import makeAnimated from 'react-select/animated';

const animatedComponents = makeAnimated();
const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

export default function Foo() {
  const [checked, setChecked] = useState([]);
  const handleChange = values => {
    setChecked(values);
  };
  const handleClick = () => {
    alert(checked.map(item => item.value).join(','));
  };
  return (
    <div>
      <Select
        components={animatedComponents}
        options={options}
        isMulti
        onChange={handleChange}
      />
      <br />
      <button
        type="button"
        onClick={handleClick}
        style={{
          border: 'none',
          padding: '0.875rem 1.75rem',
          fontSize: '1rem',
          color: 'white',
          backgroundColor: 'green',
        }}
      >
        确认
      </button>
    </div>
  );
}

试试这个。
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题