2016-08-30 2 views
7

im는 반응을 사용하고 아이를 렌더링하고 조건에 따라 클래스를 추가하기 만하면되는 컴포넌트가 있습니다. 최선의 방법은 무엇입니까? 당신은 아이까지 소품을 전달할 수 있습니다React - 자식 컴포넌트에 클래스 추가하기

var childClasses = [], 
    childClassNames; 
if (condition) { 
    childClasses.push('my-class-name'); 
} 
childClassNames = childClasses.join(' '); 

return (<div className={childClassNames}> 
    .... (your component here) 
</div>); 
+0

[이] (http://stackoverflow.com/questions/26863938/modify-attributes-of-children-in-reactjs-component) 당신을 도움이 될 것입니다. –

답변

10

내가 일주일 전에 그것을 알아 냈어,이게 내가 무엇이다 원 :

export default class ContainerComponent extends React.Component { 
    constructor(props) { 
     super(props); 

     this.modifyChildren = this.modifyChildren.bind(this); 
    } 

    modifyChildren(child) { 
     const className = classNames(
      child.props.className, 
      {...otherClassses} 
     ); 

     const props = { 
      className 
     }; 

     return React.cloneElement(child, props); 
    } 
    render() { 
     return (<div> 
      {React.Children.map(this.props.children, this.modifyChildren(child))} 
     </div>); 
    } 
} 
+1

이 솔루션을 시도했지만 렌더링 함수에서 "자식이 정의되지 않았습니다."오류가 발생합니다. 익명 함수로 변경하면 클래스 메서드 (예 : this.modifyChildren)를 호출하는 대신 오류가 사라지고 모든 것이 올바르게 작동합니다. 이는 "굵은 화살표"와 전통적인 JS 익명 함수와 함께 작동합니다. 우리 코드가 거의 동일 할 때 왜 내가 당신을 위해서가 아니라 나를 위해서 일하는 것인지 알 수 없습니다. –

0

내부는 구성 요소의 방법을 렌더링

을 자녀에

렌더링 :

const classes = []; 

if (props.contentVisible) 
    classes.push('visible'); 

<div className={classes.join(' ')} /> 
+0

각 구성 요소에서이 작업을 수행하고 싶지는 않지만 테스트를 수행하고 필요한 경우 클래스를 추가하는 구성 요소가 필요합니다. – Pachu

+0

정확히 무엇을 달성하려고하는지 잘 모름. 부모 구성 요소는 필요한 모든 클래스를 계산하여이를 소품으로 전달할 수 있습니다. – Maggie

1

그리고 적용 할 어떤 클래스를 선택할 수 있습니다 (또는 클래스 이름을 전달하지만이 더 의미이다) :

관련 문제