【问题标题】:Toggle switch without clicking List Item在不单击列表项的情况下切换开关
【发布时间】:2020-08-09 12:33:27
【问题描述】:

我目前有一个列表,其中包含一堆列表项,每个列表项都有文本和一个开/关切换按钮,我遇到的问题是,当点击切换按钮时,它也会点击整行或列表项也是如此,我想单击切换按钮而不单击整行。

我在代码中添加了一个 codeSandBox 链接以使其更容易:

https://codesandbox.io/s/material-demo-32j3b?file=/demo.js

【问题讨论】:

  • 一个简单的技巧是禁用 ListItem 上的涟漪效应。这是示例 => codesandbox.io/s/material-demo-hwi1u
  • 这对我不起作用,因为我也希望能够单独单击列表

标签: reactjs material-ui


【解决方案1】:

您可以停止从Switch 通过stopPropagation 冒泡点击事件,这样当您点击Switch 时,父母的click 事件不会被触发。

至于涟漪效应,这是由您传递给ListItembutton 属性产生的。如果您也想在单击Switch 时禁用它,您可以在单击Switch 时将ListItem 上的disableRipple 设置为true。

const [disabledRipple, setDisabledRipple] = useState(false);

useEffect(() => {
  setDisabledRipple(false);
}, [disabledRipple]); /* re-enable it afterwards */

<ListItem button style={style} key={index} disableRipple={disabledRipple}>
    <ListItemText primary={`Item ${index + 1}`} />
        <Switch
          onClick={(e) => {
            e.stopPropagation();
            setDisabledRipple(true);
          }}
        />
        ...

https://codesandbox.io/s/material-demo-t6lqh?file=/demo.js

n.b.,大写 renderRow 将其转换为 React 函数组件

【讨论】:

    【解决方案2】:

    这里有 3 件事需要注意

    • 首先,要使用Switch而不影响ListItem的点击行为,你应该使用ListItemSecondaryActionofficial doc demo here
    • 第二件事,如您所知,要正确使用react-window,我们不能忽略style(引用于doc),但是当直接使用styleListItem,结合ListItemSecondaryAction 时,它可能导致样式表中断。因此,为避免这种情况,请保持ListItem 保持清洁,不要覆盖任何样式,方法是将其包裹在一个容器周围(我使用Box)和style
    • 最后,当使用ListItemSecondaryAction 作为最后一个子元素时,ListItem (doc) 将为此使用一个额外的容器组件,默认为li 标签,因此为避免这种情况,请通过设置ContainerComponent 覆盖支持div
    function renderRow(props) {
      const { index, style } = props;
    
      return (
        <Box style={style}>
          <ListItem button key={index} ContainerComponent="div">
            <ListItemText primary={`Item ${index + 1}`} />
            <ListItemSecondaryAction>
              <Switch
                defaultChecked
                color="default"
                inputProps={{ "aria-label": "checkbox with default color" }}
              />
            </ListItemSecondaryAction>
          </ListItem>
        </Box>
      );
    
    

    以下是解决方案演示的分叉代码框

    【讨论】:

      【解决方案3】:

      您可以使用@material-ui/list-item-secondary-action。作为示例,请参阅此 https://material-ui.com/components/lists/#checkbox

      中的评论按钮

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 1970-01-01
        • 2013-10-19
        • 2021-04-18
        • 2012-11-08
        • 2014-05-30
        • 2023-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多