基于hook的ant design 的tab页的删除功能实现

点击树节点生成tab页面,点击关闭按钮,关闭tab页面

const mapDispatchToProps = dispatch => ({
  onChange: activeKey => {
    dispatch({
      type: 'centerTab/changeTab',
      payload: { activeKey },
    })
  },
  remove: targetKey => {
    dispatch({
      type: 'centerTab/removeTab',
      payload: {
        targetKey,
      },
    })
  },
})




function Test(props) {
  console.log(props)
  debugger
  const [activeKey, setActiveKey] = useState(props.activeKey)
  const [panes, setPanes] = useState(props.data)

  useEffect(() => {
    setPanes(props.data)
    setActiveKey(props.activeKey)
  }, [props.data])

  const onChange = activeKeys => {
    props.onChange(activeKeys)
  };

  const remove = targetKey => {
    props.remove(targetKey)
  };

  const onEdits = (targetKey, action) => {
  
  	// 这里OnEdits接受到的第二参数是'remove'和'add'所以可以对他进行判断
  	
    if (action === 'remove') {
      remove(targetKey)
    }
  };



return (
    <div className={mainView.center}>
      <Tabs
        hideAdd
        onChange={e => {
          onChange(e)
        }}
        activeKey={activeKey}
        type="editable-card"
        onEdit={(targetKey, action) => {
          onEdits(targetKey, action)
        }}
      >
        {panes.map(pane => (
          <TabPane tab={pane.title} key={pane.key}>
            {pane.content}
          </TabPane>
        ))}
      </Tabs>
    </div>
  );

在使用ant design 的时候关闭tab页的时候,这里

  const onEdits = (targetKey, action) => {
  
  	// 这里OnEdits接受到的第二参数是'remove'和'add'所以可以对他进行判断
  	
    if (action === 'remove') {
      remove(targetKey)
    }
  };

这里如果使用函数组件的时候,会找不到对应的函数从而无效,因为如果写法为

  onEdit = (targetKey, action) => {
    this[action](targetKey); // 这个时候this是undefined所以也是取不到的。
  };
  
  
  //或者
 onEdit = (targetKey, action) => {
     action(targetKey); // 等价于 'remove'(targetKey),这样是找不到这个函数的
   };
  

posted on 2019-11-14 20:56  2481  阅读(1001)  评论(0编辑  收藏  举报

导航