javascript-React钩子无法通过事件处理程序工作

前端之家收集整理的这篇文章主要介绍了javascript-React钩子无法通过事件处理程序工作 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

反应版本:16.8.2

const { useState } = React;

const Dropdown = ({
  options,onClick,selected,}) => {
  const [showDropDown,setShowDropDown] = useState(false);

  function toggleDropDown() {
    setShowDropDown(v => !v);
  }

  function createOption(o) {
    return (
      <div
        key={o}
        className='drop-down__option'
        onClick={() => {
          onClick(o);
          toggleDropDown();  
          // The following isn't working either
          // setShowDropDown(false);
        }}
       >
        {o}
      </div>
    );
  }

  return (
    <div
      onClick={toggleDropDown}
      className='drop-down'
    >
      <div>{selected}</div>
        {showDropDown && (
          <div className='drop-down__list'>
            {options.map(createOption)}
          </div>
        )}
    </div>
  );
};

const App = () => {
  const [selected,setSelected] = useState(0);

  return (
    <Dropdown
      selected={selected}
      options={[0,1,2,3]}
      onClick={v=>{setSelected(v)}}
    />
  );
}

ReactDOM.render(
  <App />,document.getElementById('root'),);

因此,这是一个简单的下拉菜单,当您单击容器时,它会切换下拉菜单.

But the problem here is,after clicking one of the options,the option has been updated,but the Dropdown is not been closed.

如此看来toggleDropDown();在下面的代码中无效.

        onClick={() => {
          onClick(o);
          toggleDropDown();  
          // The following isn't working either
          // setShowDropDown(false);
        }}

重现示例可以在这里找到:https://codepen.io/vensa-albertgao/pen/ommGZe

我错过了什么?

最佳答案
您的代码中的问题在于,即使下拉菜单上的单击也被传播到了父级,在父级上您再次在onClick上调用toggleDropdown,因此切换发生了两次,导致看不到它.您所需要做的就是在选项上停止传播

const { useState } = React;

const Dropdown = ({
  options,setShowDropDown] = useState(false);

  function toggleDropDown() {
    console.log('called');
    setShowDropDown(v => { console.log(v); return !v});
  }

  function createOption(option) {
    return (
      <div
        key={option}
        className='drop-down__option'
        onClick={e => {
          e.stopPropagation();
          onClick(option);
          toggleDropDown();  
        }}
       >
        {option}
      </div>
    );
  }

  return (
    <div
      onClick={toggleDropDown}
      className='drop-down'
    >
      <div>{selected}</div>
        {showDropDown && (
          <div className='drop-down__list'>
            {options.map(createOption)}
          </div>
        )}
    </div>
  );
};

const App = () => {
  const [selected,);

Working demo

原文链接:https://www.f2er.com/js/531163.html

猜你在找的JavaScript相关文章