【问题标题】:Using Grid with SortableJS将 Grid 与 SortableJS 一起使用
【发布时间】:2020-01-06 09:57:38
【问题描述】:

我将SortableJS 用于React,并尝试实现水平Grid,因此最终结果将如下所示:

我设法做到了,但是排序功能根本不起作用。我认为这与tag 属性有关。当我尝试tag={Grid} 时出现以下错误:

可排序:el 必须是 HTMLElement,而不是 [object Object]

任何想法如何将Grid 实现到tag 属性?这是我的代码:

     <Grid container>
            <Sortable options={{ fallbackOnBody: true, group: "items", handle: reorderHandle }} tag={Grid} onChange={handleChange}>
                {items.map((item, index) =>
                    <Paper key={index} data-id={index} className={classes.item} elevation={0}>
                        <ButtonHelper {...getHandleClass(editable)} key={index} icon={
                            <Badge badgeContent={index + 1} color="default">
                                {editable && <ReorderIcon />}
                            </Badge>}
                        />
                        <Grid item xs={4} key={index}>
                            <div className={classes.gridItem}>
                                <GalleryInput className={classes.image} style={{ width: '300px' }} label="image" source={`${source}[${index}].image`} />
                                <br></br>
                                <TextInput label="desc" source={`${source}[${index}].desc`} />
                                {editable && <ButtonHelper icon={<RemoveIcon />} onClick={handleRemove(index)} className={classes.left} />}
                            </div>
                        </Grid>
                    </Paper>
                )}
            </Sortable>
        </Grid>

感谢您的帮助。

【问题讨论】:

    标签: reactjs grid sortablejs


    【解决方案1】:

    由于您使用的是自定义组件,因此 tag 属性仅接受它作为 forwarRef 组件。

    所以你需要以这种方式更新。

    示例片段

    // This is just like a normal component, but now has a ref.
    const CustomComponent = forwardRef<HTMLDivElement, any>((props, ref) => {
      return <div ref={ref}>{props.children}</div>;
    });
    
    export const BasicFunction: FC = props => {
      const [state, setState] = useState([
        { id: 1, name: "shrek" },
        { id: 2, name: "fiona" }
      ]);
    
      return (
        <ReactSortable tag={CustomComponent} list={state} setList={setState}>
          {state.map(item => (
            <div key={item.id}>{item.name}</div>
          ))}
        </ReactSortable>
      );
    };
    

    【讨论】:

    • 这对我的情况有所帮助。一旦我将 forwardRef 添加到我的自定义组件中,它就会按预期工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2015-12-30
    • 2018-12-11
    相关资源
    最近更新 更多