2016-06-15 6 views
4

내가 가진 결과 중 하나를 무시 : this.props 내부Destructuring 객체와

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

, 나는 내가 복제 된 요소에 전달하지 않는 styles 속성이 있습니다.

어떻게하면됩니까?

+0

지금은'... this.props' 다음에'styles : null'을 정의하고 있습니다 만 작동하지만 슈퍼 좋은 없습니다. –

+0

내 대답을 시도 했습니까? – ctrlplusb

+0

네, 전에'styles'가 이미 정의 되었기 때문에 미안 해요. –

답변

9

당신이 사용할 수있는 object rest/spread syntax :

// 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 stage 1 preset. 실행 중에 구문 오류가 발생하면 다음과 같이 사전 설정을 설치할 수 있습니다.

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

그런 다음 바벨 구성의 사전 설정 섹션에 추가하십시오. 당신의 .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, 
}); 
+1

반응이 사전 설정되어있는 상태에서이 기능이 작동하지 않는다고 생각합니다. 이 기능을 사용하도록 Babel을 구성하는 방법을 설명하면 유용 할 것입니다. –

+0

이것은 정말 창의적인 답변입니다. 이것이 스프레드 연산자로 가능하다는 것을 알지 못했습니다. –

0

내가 ctrlplusb의 답변을 좋아하지만, 여기 당신이 미리 새로운 바벨 추가하지 않으려면 Object.assign를 사용하여 대안 :

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

그런 다음 정의되지 않은 속성이 있습니다. –

+0

응용 프로그램에 차이가 없어야합니다. 컴포넌트로 전달되지 않은'prop'를 접근하려고하면 값은'undefined'가됩니다. 소품에 제공된 특정 키의 존재에 의존하지 않는다면 거의 동일합니다. –

0

또는 당신이 할 수있는가 이런 식으로 ...

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