在 React 无状态函数式组件中,我们通常会这样写:
export function MyCompoment({
title,
foo,
bar
}) {
return <div> title: {title}, ...</div>
}
我们立即将 props 对象解构为其变量。
现在我正在使用 Material-UI makeStyles
Hook ,我也在使用 TypeScript,我目前使用它的方式如下所示。
const useStyles = makeStyles((theme : Theme ) =>({
root: ({foo} : MyComponentProps) => ({
content: foo
})
});
interface MyComponentProps {
title: string;
foo: string;
bar: string;
}
export function MyCompoment({
title,
foo,
bar
} : MyComponentProps) {
const classes = useStyles({
title,
foo,
bar
});
return <div> title: {title}, ...</div>
}
您可以看到问题 - 我必须重复 props 变量名称才能传递到类中。
我认为避免这种情况的最好方法是这样写:
export function MyCompoment(props: MyComponentProps) {
const {
title,
foo,
bar
} = props;
const classes = useStyles(props);
return <div> title: {title}, ...</div>
}
但这比我想要的要困惑一些。
我想知道是否可以这样做:
export function MyCompoment({
title,
foo,
bar
} = props : MyComponentProps) {
const classes = useStyles(props);
return <div> title: {title}, ...</div>
}
我知道我很挑剔,只是想知道。
最佳答案
没有(大部分)
来自语法:
很难证明是否定的,所以我不得不去语法。
据我所知,Typescript 没有提供 javascript 没有的任何额外的解构能力,所以我只针对 javascript 回答这个问题。
在 ES6 语法中,单个函数参数无法在一个参数中同时被析构并在参数列表中指定名称。
如果您查看 ES6 grammar对于 FormalParameter
,它是参数列表中的一个东西,你会发现它只能是一个 BindingElement
,它要么是一个 SingleNameBinding
或 BindingPattern
— 不能同时使用。绑定(bind)模式只能进行解构,单名称绑定(bind)只能分配给一个值,因此无法同时进行。
(请注意,我链接的语法只是某人放在 github 上的要点。我不认为有人会在 github 上发布误导性的 ES6 语法,但如果您持怀疑态度,您可以随时查看不太方便的官方语法。)
可能还有其他一些我错过的疯狂方法,但我以前从未见过,我会感到非常惊讶。
如果你真的想...
你是“你能想到的最佳方式”也是我能想到的最佳方式。你应该这样做。
不过,我不喜欢回答“否”,所以如果您真的想在参数列表中获取所有内容,您可以做一些不愉快的事情。如果你这样做:
function assignAndDestructure(props, { foo, bar } = props) {
// props, foo, and bar will all be assigned
}
哪种符合您的标准。然而,它创建了一个可选的第二个参数,调用者可以滥用它来破坏你的解构。您可以通过将其分配给 Typescript 中没有该参数的类型来隐藏它,但这仍然存在风险。
综上所述,没有好办法,只有坏办法。选择您提到的“您能想到的最好的”。
关于javascript - 有没有办法既解构函数参数,又保留对参数的命名引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56352702/