2017-11-01 40 views
1

date을 받침으로 받아 들일 수있는 재사용 가능한 시간 표시 줄을 만들고 leftright (예 : ceil 또는 floor date ... 잠재적으로 더 많은 논리가 포함될 수 있음) 두 개의 날짜를 반환합니다.형제 사이에 의사 소통하기 React

leftright을 수락 할 다른 구성 요소 (그래프 등)를 타임 라인과 연결할 수있는 소비자에게이를 알리는 가장 좋은 방법을 알아 내려고합니다. 부모

는 (자식 1로 날짜를 전달 날짜를 받아 자식 2로 전달)

->자식 1 (자식 1은 소품 날짜를 기준으로 제작 한 TimeBar가, 왼쪽 및 오른쪽 날짜를 생성하는 것)에 전달

->자식 2 (이 자식 1에서 왼쪽 및 오른쪽 일자 필요)

나는 2 옵션을 검토 한 결과 :

콜백 경로 : 부모는 날짜와 콜백을 전달하여 상태를 왼쪽과 오른쪽으로 업데이트합니다. 그런 다음 필요로하는 그래프에 대해이 왼쪽, 오른쪽 날짜를 사용합니다. 이것은 부모를 필요로 논리

http://jsbin.com/jikoya/edit?js,console,output

또는

별도 ES6 클래스는이 클래스를 인스턴스화하고 강화 왼쪽을 반환 바로 사용할 준비가 올라간다. 그런 다음이를 상태에 추가하고 모든 구성 요소로 전달하십시오.

constructor(props) { 
    super(props); 
    this.timebar = new Timebar(new Date('01-16-2016')) 
    this.state = { 
     leftDate: this.timebar.leftDate, 
     rightDate: this.timebar.rightDate 
    } 
    } 
render(){ 
    return(
      <timebarObj={this.timebarObj} /> 
      <graph leftDate={this.state.leftDate} rightDate={this.state.rightDate}/> 
    ) 
} 

이 별도의 클래스 방법을 수행하는 단점은 무엇입니까? 내가 볼 수있는 이점은이 전체 인스턴스를 통해 소품 내에서 훨씬 더 많은 것을 전달할 수 있다는 것입니다. 아이가 컨테이너의 독립적 인 자신의 상태를 추적 할려고하는 경우에 당신이 정말로 통제되지 않은 구성 요소에 대 제어 무슨 말을하는거야

+0

: 부모가 자신의 상태보다 아이의 상태에 대해 알 필요가있는 경우 부모 (두 번째 예)

두 번째 예 외에 또 다른 옵션 사용 "소품 렌더링"하는 것입니다에서 불과 와야한다 나는 둘 다 옵션 2와 함께 갈 것이다. 둘 다 [리프팅 상태] (https://reactjs.org/docs/lifting-state-up.html)의 예제이지만, 논리가있는 단일 부모와 stateless (멍청한) 그냥 소품을 받고 물건을 렌더링하는 아이들. – pawel

+0

@Dhaval Patel은 내 대답을 아래에 의미가 있습니까? – Maxwelll

+0

@Maxwelll 네, 완벽하게 이해합니다. 렌더링 소품 메서드는 각 중첩 된 자식을 복제하고 소품을 전달하는 것보다 분명합니다. 많은 감사합니다. –

답변

2

... https://reactjs.org/docs/forms.html#controlled-components

이 조절되지 않는해야합니다.

class Child extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     leftDate: "", 
     rightDate: "" 
    } 
    this.calcDates = this.calcDates.bind(this) 
    } 

    componentDidMount(){ 
    this.calcDates(this.props); 
    } 

    componentWillReceiveProps(nextProps){ 
    if (nextProps.origDate !== this.props.origDate) { 
     this.calcDates(nextProps) 
    } 
    } 

    calcDates = (nextProps) => { 
    console.log("Child: calcDates", nextProps) 
    const lf = nextProps.origDate + " left date"; 
    const rt = nextProps.origDate + " right date"; 
    this.setState({leftDate: lf, rightDate: rt}, this.sendToParent) 
    } 


    render() { 
    return this.props.children(this.state) 
    } 
} 

class Parent extends React.Component { 
    render() { 
    return (
     <div> 
     <Child> 
     { state => (
      JSX that relies on state from child... 
     ) 
     } 
     </Child> 
     </div> 
    ) 
    } 
}