2017-09-11 3 views
1

부모 구성 요소의 업데이트 된 상태 address을 자식 구성 요소의 center 속성에 전달하고 싶습니다. App 구성 요소에서 BaseMap 구성 요소에 이르기까지 더욱 자세하게 설명합니다. 그러나, 나는 그것을 작동하게하는 것처럼 보일 수 없다. 도움이 될 수있는 눈의 신선한 쌍이 감사하게 될 것입니다!React JS에서 부모와 자식 구성 요소의 업데이트 된 상태를 전달하십시오.

부모 :

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     avatar: '', 
     username: 'nickname93', 
     realName: '', 
     location: '', 
     followers: '', 
     following: '', 
     repos: '', 
     address: '' 
     } 
    } 

    render() { 
    return (
     <div> 
     <SearchBox fetchUser={this.fetchUser.bind(this)}/> 
     <Card data={this.state} /> 
     <BaseMap center={this.state.address}/> 
     </div> 
    ); 
    } 

    fetchApi(url) { 
    // some fetch functionality 
    } 

    fetchUser(username) { 
    let url = `https://api.github.com/users/${username}`; 

    this.fetchApi(url); 
    } 

    componentDidMount() { 
    let url = `https://api.github.com/users/${this.state.username}`; 

    this.fetchApi(url); 
    } 

} 

는 (. 그것은 당신을 귀찮게하지 않도록 난 그냥 내 하위 구성 요소의 상태를 업데이트 할 필요가 잘 작동, 내가 가져 오기 기능을 삭제) 내 코드는

그리고 하위 구성 요소 :

export default class BaseMap extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      center: [24, 56], 
      zoom: 11 
     } 
    } 

    render() { 
     return (
      <Col md={10} mdPull={1}> 
       <div className="map"> 
        <GoogleMap 
        bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'} 
        center={this.state.center} 
        zoom={this.props.zoom}> 
        </GoogleMap> 
       </div> 
      </Col> 
     ); 
    } 
} 

답변

2

귀하의 가치 은 부모 구성 요소 App에서 하위 구성 요소 BaseMap으로으로 전달됩니다.

당신은 간단하게 액세스하거나 (도 props라고도 함) 속성을 사용할 수는 this.props.center 대신 this.state.center를 사용하여 부모로부터 자식 구성 요소에 전달.

export default class BaseMap extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     center: [24, 56], 
     zoom: 11 
    } 
} 

render() { 
    return (
     <Col md={10} mdPull={1}> 
      <div className="map"> 
       <GoogleMap 
       bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'} 

       center={this.state.center} // this is [24,56] 

       centerFromParentComponent = {this.props.center} // this is the property passed from parent component 

       zoom={this.props.zoom}> 
       </GoogleMap> 
      </div> 
     </Col> 
    ); 
} 

}

당신이 당신의 부모 구성 요소에서 전달하는 (예 : 변수 상태, 또는 방법 등) 모든 속성에 액세스 할 수 있습니다 this.props 사용.

componentWillReceiveProps() 방법을 살펴볼 수도 있습니다. 곧 필요할 수도 있습니다.

1

this.props.center를 사용하는 대신 this.state.center 당신은 BaseMap 부모에서 상태 업데이트를 수신하려면. center 소품에 대한 기본값을 설정하려는 것 같습니다. 여기에 the doc이 기본 소품을 선언합니다.

관련 문제