![](/img/trans.png)
[英]How to access props in react functional component using react and typescript?
[英]How to pass the props to react functional component using react table and typescript?
我想通過兩個 arguments 使用反應表和 typescript 反應功能組件。
下面是我的代碼,
type NameCellValue = {
name: string;
type: string;
}
type NameCellProps = {
value: NameCellValue;
mode: Mode;
canOpen: boolean;
}
const NameCell: React.FC<NameCellProps> = ({
value: {name,type},
mode,
canOpen
}) => {
console.log(mode) //this is undefined
console.log(canOpen) //this is undefined
canOpen: boolean,
}
const buildColumns : (
mode: Mode,
canOpen?: boolean
) => Column<Data>[] = (mode, canOpen) => [
{
Header: 'Name',
id: 'name',
accessor: ({name, type}) => ({
name,
type,
}),
Cell: NameCell(mode, canOpen), //how do i pass mode and canOpen to NameCell
} as Column<Data, NameCellProps['value'] | NameCellProps['mode] | NameCellProps['canOpen']>,
];
const ParentComponent = () => {
const columns = buildColumns(mode, canOpen);
return (
//some jsx
);
}
以上不起作用。 它給出錯誤“模式類型的參數不可分配給在線 PropsWithChildren 類型的參數
Cell: NameCell(mode, canOpen)
同樣,當我在 NameCell 中記錄 mode 和 canOpen 的值時,它們是未定義的。
有人可以幫我解決這個問題。 謝謝。
您應該始終使用尖括號語法渲染反應組件,例如:
<NameCell value={value} mode={myModeHere} canOpen />
可以直接調用 function,但您必須將 props 作為 object 傳遞,例如:
NameCell({ value, mode: myModeHere, canOpen: true })
但是除非你有充分的理由,否則請像第一個示例一樣使用尖括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.