我应该使用什么道具来格式化 mui 数据网格 React js 中的电话号码字段?

问题描述 投票:0回答:1

嗯,在纯 html 中,我对输入字段使用了模式属性,但现在我没有任何输入字段。 我应该怎么办? 你能给我一个 mui doc 中的参考吗?

const columns = [
    {
      field: "first_name",
      headerName: "First Name",
      width: 180,
      editable: true,
      
    },
    {
      field: "last_name",
      headerName: "last Name",
      width: 180,
      align: "left",
      headerAlign: "left",
      editable: true,
    },
    {
      field: "phone",
      headerName: "phone",
      width: 180,
      editable: true,
      // pattern: "[0-9]{3}-[0-9]{3}-[0-9]{4}",
    },
    
  ];
javascript material-ui format mui-datatable
1个回答
0
投票

GridColDef 接口允许传递自定义 renderEditCell 参数,因此您可以将任何想要的参数传递给 udnerlying 组件

function CustomEditComponent(props: GridRenderEditCellParams) {
  return <input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" value={params.value} onChange={...} />;
}

const columns: GridColDef[] = [
  {
    field: "phone",
    headerName: "phone",
    editable: true,
    renderEditCell: (params: GridRenderEditCellParams) => (
      <CustomEditComponent {...params} />
    ),
  },
];

但是比这更复杂一点,因为新值必须传递给 API。

function CustomEditComponent(props: GridRenderEditCellParams) {
  const { id, value, field, hasFocus } = props;
  const apiRef = useGridApiContext();

  const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value; // The new value entered by the user
    apiRef.current.setEditCellValue({ id, field, value: newValue });
  };

  return <input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" value={params.value} onChange={handleValueChange}  />;
}
© www.soinside.com 2019 - 2024. All rights reserved.