source

개체를 파괴하고 결과 중 하나를 무시하는 중

bestscript 2023. 3. 16. 21:34

개체를 파괴하고 결과 중 하나를 무시하는 중

다음과 같은 것이 있습니다.

const section = cloneElement(this.props.children, {
  className: this.props.styles.section,
  ...this.props,
});

안에서.this.props, 나는 가지고 있다.styles복제 요소에 전달하지 않을 속성입니다.

어떻게 해야 할까?

오브젝트 rest/spread 구문을 사용할 수 있습니다.

// We destructure our "this.props" creating a 'styles' variable and
// using the object rest syntax we put the rest of the properties available
// from "this.props" into a variable called 'otherProps' 
const { styles, ...otherProps } = this.props;
const section = cloneElement(this.props.children, {
  className: styles.section,
  // We spread our props, which excludes the 'styles'
  ...otherProps,
});

위의 코드에 근거해, 이 구문은 이미 서포트되고 있다고 생각합니다만, 이것은 babel 스테이지 1의 프리셋으로 이용 가능한 제안 구문입니다.실행 시 구문 오류가 발생할 경우 다음과 같이 사전 설정을 설치할 수 있습니다.

 npm install babel-preset-stage-1 --save-dev

그런 다음 babel 구성의 사전 설정 섹션에 추가합니다.예를 들어 .babelrc 파일:

 "presets": [ "es2015", "react", "stage-1" ]

OP의 질문에 대한 코멘트를 바탕으로 갱신합니다.

좋아, 그럼 넌 이미 한 명이라도 있다고?styles변수가 이 블록 전에 선언되었습니까?이 사건도 우리가 처리할 수 있어요.이를 피하기 위해 비구조화된 인수의 이름을 변경할 수 있습니다.

예를 들어 다음과 같습니다.

const styles = { foo: 'bar' };

const { styles: otherStyles, ...otherProps } = this.props;
const section = cloneElement(this.props.children, {
  className: otherStyles.section,
  // We spread our props, which excludes the 'styles'
  ...otherProps,
});

Object Rest Spread 연산자 마법을 사용할 수 있습니다.

const props = { a: 1, b: 2, c: 3 };
const { a, ...propsNoA } = props;
console.log(propsNoA); // => { b: 2, c: 3 }

고객의 경우는 다음과 같습니다.

const { styles, ...propsNoStyles } = this.props;
const section = cloneElement(this.props.children, {
  className: this.props.styles.section
  ...this.propsNoStyles,
});

아니면 이런 걸 할 수도 있고

var newProp = (this.props = {p1, p2,...list out all props except styles});

ctrlplusb의 답변은 좋지만 새로운 babel 프리셋을 추가하지 않으려면 Object.assign을 사용하는 다른 방법이 있습니다.

const section = cloneElement(this.props.children, {
    className: this.props.styles.section,
    ...Object.assign({}, this.props, {
        styles: undefined
    })
});

언급URL : https://stackoverflow.com/questions/37838778/destructuring-object-and-ignore-one-of-the-results