解构嵌套对象:如何获取父级及其子级值?

sou*_*ubi 7 javascript destructuring reactjs react-ref

在下面的函数中,我得到了带有属性的textarea对象current.

这里,嵌套的解构与StartEnd变量一起工作.但current变量不起作用.

function someFunction({ current: { selectionStart: Start, selectionEnd: End } }, AppStateSetter) {

    // do something with current, Start, and End
}
Run Code Online (Sandbox Code Playgroud)

adi*_*iga 10

第一次解构只创造StartEnd变量.如果要创建current变量,则需要再次声明它.

function ({ current: { selectionStart: Start, selectionEnd: End }, current }, AppStateSetter) {

// do something with current , Start , and End

}
Run Code Online (Sandbox Code Playgroud)

你可以在Babel编译器上测试它:

这段代码:

const object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
}

const { current: { selectionStart: Start, selectionEnd: End } } = object;
Run Code Online (Sandbox Code Playgroud)

获取trasnpiled到:

var object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
};

var _object$current = object.current,
    Start = _object$current.selectionStart,
    End = _object$current.selectionEnd;
Run Code Online (Sandbox Code Playgroud)

如您所见,current未创建变量.