reactjs 如何在React-Table中添加新的可编辑行?

btqmn9zl  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(282)

bounty将在3天后过期。回答此问题可获得+50声望奖励。Xkoder FX希望引起更多人关注此问题。

我正在使用React-Table构建一个动态表,我想添加一个新的可编辑单元格行。目前我可以添加新行,但只有当我按下全局编辑按钮时,我才可以编辑它,相反,我想添加一个行,这将是可编辑的第一。这是我的代码-
主要成分

function StyledTable() {
  useEffect(() => {
    dispatch(getData(mokeJsonData));
  }, []);
  const [datatoColumns] = useState(columnDataaa.slice(1));
  const [skipPageReset, setSkipPageReset] = useState(false);
  const data = useSelector((state) => state.dataReducer.data);
  const dispatch = useDispatch();

  const columns = useMemo( 
    () => [
      {
        Header: "",
        id: "expander", 
        Cell2: ({ row }) => { 
          return (
            <span {...row.getToggleRowExpandedProps()}>  
              {row.isExpanded ? "-" : "+"}
            </span>
          );
        },
        Cell: () => {
          return <div></div>;
        },
      },
      {
        Header: columnDataaa[0].Header,
        accessor: columnDataaa[0].accessor,
        Cell: ({ value, row }) => {
          return (
            <FlexDiv>
              <HighlightOffIcon
                style={{ marginRight: "5px", color: "grey", width: "20px" }}
                onClick={() => dispatch(deleteRow(row.index))}
              />
              {value}
            </FlexDiv>
          );
        },
      },
      ...datatoColumns,
    ],
    []
  );

  useEffect(() => {
    setSkipPageReset(false);
  }, [data]);

  const renderRowSubComponent = useCallback(
    ({ row }) => ({
      values: row.original.addInfo && row.original.addInfo,
    }),
    []
  );
  return (
    <Styles>
      <h1>הגדרת מנהל</h1>
      <Table
        columns={columns}
        skipPageReset={skipPageReset}
        renderRowSubComponent={renderRowSubComponent}
      />
    </Styles>
  );
}

export default StyledTable;

可编辑单元格

const EditableCell = ({
  value: initialValue,
  row: { index },
  column: { id, editable, type, width, valueOptions },
}) => {
  const [value, setValue] = useState(initialValue);

  const onChange = (e) => {
    setValue(e.target.value);
  };
  const dispatch = useDispatch();

  const onBlur = () => {
    if (value === "") return alert("requiredddd");
    return dispatch(updateMyData({ index, id, value }));
  };

  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]); 

  if (type === "singleSelect")
    return (
      <InputSelect
        value={value}
        onChange={onChange}
        onBlur={onBlur}
        style={{ width: width }}
      >
        {valueOptions.map((item, i) => {
          return (
            <option value={item.label} key={i}>
              {item.label}
            </option>
          );
        })}
      </InputSelect>
    );
  if (type === "date")
    return (
      <DatePicker
        style={{ width: width }}
        type="date"
        disabled={editable === false}
        value={value}
        onChange={onChange}
        onBlur={onBlur}
      />
    );
  return (
    <input
      style={{ width: width }}
      disabled={editable === false}
      value={value}
      onChange={onChange}
      onBlur={onBlur}
    />
  );
};

export default EditableCell;

添加行函数

addRow: (state, action) => {
      const obj = {};
      action.payload.slice(1).forEach((item) => {
        obj[item.accessor] = '';
      });
      if (
        obj &&
        Object.keys(obj).length === 0 &&
        Object.getPrototypeOf(obj) === Object.prototype
      )
        return;
      else {
        state.data.splice(0, 0, obj);
        state.originalData = state.data;
      }
    },


谢谢

ljsrvy3e

ljsrvy3e1#

将state变量和方法传递给useTable()根钩子。自定义插件钩子和其他维护组件状态的变量/方法将从表示例返回。稍后您可以从任何地方获取这些钩子和方法。

const {
    // all your hooks...
  } = useTable(
    {
      columns,
      data,
      // all your other hooks...
      updateMyData,
      // pass state variables so that we can access them in edit hook later
      editableRowIndex, // index of the single row we want to edit 
      setEditableRowIndex // setState hook for toggling edit on/off switch
    },
    // other hooks... 
    (hooks) => {
      hooks.allColumns.push((columns) => [
        // other hooks such as selection hook
        ...columns,
        // edit hook
        {
          accessor: "edit",
          id: "edit",
          Header: "edit",
          Cell: ({ row, setEditableRowIndex, editableRowIndex }) => (
            <button
              className="action-button"
              onClick={() => {
                const currentIndex = row.index;
                if (editableRowIndex !== currentIndex) {
                  // row requested for edit access
                  setEditableRowIndex(currentIndex);
                } else {
                  // request for saving the updated row
                  setEditableRowIndex(null); // keep the row closed for edit after we finish updating it
                  const updatedRow = row.values;
                  console.log("updated row values:");
                  console.log(updatedRow);
                  // call your updateRow API
                }
              }}
            >
              {/* single action button supporting 2 modes */}
              {editableRowIndex !== row.index ? "Edit" : "Save"}
            </button>
          )
        }
      ]);
    }
  );

你可以从下面的链接找到例子
github存储库链接:https://github.com/smmziaul/only-one-row-editable
代码沙盒链接:https://codesandbox.io/s/github/smmziaul/only-one-row-editable

相关问题