zit*_*hir 2 javascript destructuring reactjs
有没有办法只解构函数参数中的某些对象属性,而其余的属性仍可在对象中访问?
考虑以下反应示例。(我以React为例,但这个问题一般适用于JS)
const Form = (formProps) => {
return (
...
<FormSectionComponent
initialValues={...}
values={...}
{...formProps}
/>
...
)
}
const FormSectionComponent = ({ initialValues, values}) => {
...
}
Run Code Online (Sandbox Code Playgroud)
传入的内容props在函数参数中被解构,但是,还有其他道具进来,我可能想在某些条件下访问这些道具,但我不想或无法解构 - 例如,我不知道它们是什么并且想记录他们。
有没有办法不解构参数部分中的其他道具并将它们作为props对象访问?
我能想到的唯一解决方法是:
const FormSectionComponent = (props) => {
const { initialValues, values} = props;
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否还有其他解决方案。
你可以做类似的事情
const FormSectionComponent = ({ initialValues, values, ...props}) => {
...
}
Run Code Online (Sandbox Code Playgroud)
它本质上绑定props到传递给函数的参数的其余属性。
const FormSectionComponent = ({ initialValues, values, ...props}) => {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1648 次 |
| 最近记录: |