2016-11-04 3 views
1

자녀가 부모의 소도구에 어떻게 액세스 할 수 있습니까? 예를 들어,ReactJS - 자녀가 부모의 소품에 어떻게 액세스합니까?

부모 구성 요소 - footer.jsx :

import React from 'react'; 
import $ from 'jquery'; 

import NavItem from './nav-item'; 

class Footer extends React.Component 
{ 
    constructor(props) { 
     super(props); 
     this.state = { 
      publicUrl: null, 
      currentUrl: null, 
      navitems: [], 
     }; 
    } 

    // Then fetch the data using $.getJSON(): 
    componentDidMount() { 
     this.serverRequest = $.getJSON(this.props.source, function (result) { 
      this.setState({ 
       currentUrl: window.location.href, 
       publicUrl: result.publicUrl, 
       navitems: result.nav 
      }); 
     }.bind(this)); 
    } 

    componentWillUnmount() { 
     this.serverRequest.abort(); 
    } 

    render() { 
     var loop = this.state.navitems.map(function(item, index){ 
      return <NavItem key={index} item={item}></NavItem>; 
     }); 

     return (
      <div> 
       <div className="nav"> 
        <ul>{ loop }</ul> 
        <p>{this.state.publicUrl}</p> 
        <p>{this.state.currentUrl}</p> 
       </div> 
      </div> 
     ) 
    } 
} 

export { Footer as default } 

자식 요소 --item.jsx NAV : '반응'에서 반작용

가져 오기; footer.jsx (부모)의

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

    render() { 
     return <li><a href={this.props.publicUrl + '/' + this.props.item.url}>{this.props.item.title}</a></li> 
    } 
} 

export { NavItem as default } 

결과 : nav-item.jsx (자식)에서

this.props.publicUrl // http://my-website.com 

결과 :

this.props.publicUrl // undefined but it should be http://my-website.com 

어떤 아이디어가?

샘플 데이터 :

{ 
    "publicUrl": "http:\/\/my-website.com", 
    "nav": [{ 
     "navId": "3", 
     "title": "Home 
     "code": "home 
     "href": null, 
     "style": null, 
     "sort": "3", 
     "url": "home 
     "parentId": null, 
     "totalChildren": "0", 
     "createdOn": null, 
     "updatedOn": null 
    }, { 
     "navId": "4", 
     "title": "About 
     "code": "about 
     "href": null, 
     "style": null, 
     "sort": "4", 
     "url": "about 
     "parentId": null, 
     "totalChildren": "0", 
     "createdOn": null, 
     "updatedOn": null 
    }, { 
     "navId": "5", 
     "title": "Contact", 
     "code": "contact", 
     "href": "#contact", 
     "style": null, 
     "sort": "5", 
     "url": "contact", 
     "parentId": null, 
     "totalChildren": "0", 
     "createdOn": null, 
     "updatedOn": null 
    }] 
} 
+1

당신이'' – naortor

답변

1

나는에 this를 결합해야합니다 하위 구성 요소에 정의되지 않은 값을 확인 루프 :

var loop = this.state.navitems.map(function(item, index){ 
      return <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>; 
}.bind(this)); 
+1

이 작동하는 경우 내 대답을 upvote하시기 바랍니다 –

+0

이미 않았다. 감사! :-D – laukok

+1

또한 내 답변에 표시가 올바른지 확인하십시오. 그러면 녹색 진드기가 나타납니다. –

1

여기에 체크

http://jsfiddle.net/z5m56sqn/

그렇지 않으면 경고 문제 반응 때문에 우리가 널 컨텍스트에 바인딩 this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

주를 사용하는 것도 가능하다 자동 바인딩 시스템과 관련된 null을 사용하면 함수 컨텍스트를 변경하지 않으려는 것을 의미합니다. 참조.

0

값을 prop으로 부모로부터 하위로 전달해야합니다. 그렇지 않으면 실제로 가능하지 않습니다.

var loop = this.state.navitems.map(function(item, index){ 
    return <NavItem key={index} publicUrl={this.props.publicUrl} item={item}></NavItem>; 
}); 

지금, NavItem 부모의 publicUrl 소품 동일 소품 publicUrl이있을 것이다 :

코드에서 할 일은

위의이 작은 수정이다. 그래서 기본적으로 : footer.jsx에서

결과 (부모) : 항법 item.jsx에서

this.props.publicUrl // http://my-website.com 

결과 (아이) :

this.props.publicUrl // http://my-website.com 

또는 하지만 권장하지 않습니다 귀하의 경우에을 사용하면 NavItem 기능을 소품으로 사용할 수 있습니다. 이 함수는 부모에서 정의 할 수 있으며 prop (또는 state 또는 해당 구성 요소에 대해 로컬 인 모든 값)의 값을 반환합니다.부모에 그래서 예를 들면

은 :

_getPublicUrl =() => { 
    return this.props.publicUrl; //or any kind of value, local or otherwise 
} 
...... 
var loop = this.state.navitems.map(function(item, index){ 
    return <NavItem key={index} getPublicUrl={this._getPublicUrl} item={item}></NavItem>; 
}); 

그런 다음 NavItem이 함수를 호출 할 수 있습니다에서 : 다시

var parentPublicUrl = this.props.getPublicUrl(); 

을, 특히이 경우에는 권장되지 않습니다. 그러나 state 값 또는 일부 Ajax 호출 등을 통해 가져온 변수를 얻는 유용한 방법입니다.

+0

감사하지만 내가 그것을해야한다고 생각'publicUrl 등의 소품을 통해 전달한다 = {this.state.publi cUrl}' – laukok

+0

@teelou, 글쎄, 이제 당신이 말했을 때,'publicUrl'이 부모님의'prop' 나'state'라면 약간 혼란 스럽습니다. 귀하의 질문은 * 자녀가 부모의 소도구에 어떻게 접근합니까? * ... "부모 소도구"- 상태가 아닙니다. 그러면 코드에서 '상태'인 것 같습니다. 어떤거야? : D --- 그럼에도 불구하고, 상태라면'this.state.publicUrl'을 사용하십시오. 그렇지 않으면 위와 같이 사용하십시오. – Chris

+0

이 오류는'Uncaught TypeError : 'publicUrl = {this.props.publicUrl}'에 대해 'props'undefined'를 읽을 수 없습니다. – laukok

2

하위 구성 요소의 상위 소품에 액세스 할 수있는 방법이 없습니다. 두 가지 방법을 다음에이를 수 있습니다 : - 부모로부터 아이 컴퍼넌트에

  1. 패스 값을 같은 소품을 통해 : - <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>합니다.
  2. 상태에서 값을 가져오고 상태에서 값을 가져 오기 위해 자식에서 발송 작업을 지정합니다.

또한, 나는 당신이 componentDidMount에 상태 값을 설정하는 것을 알 수 있으므로 설정 기본 생성자의 상태 값 또는 중 하나는

+0

이 오류는'Uncaught TypeError : 'publicUrl = {this.props.publicUrl}'에 대해 'props'undefined'를 읽을 수 없습니다. – laukok

+0

루프에 'this'를 바인딩해야합니다. 아래 내 대답을 참조하십시오. – laukok

관련 문제