2016-11-27 1 views
0

내 응용 프로그램에는 항목 목록을 렌더링하는 목록보기가 있습니다.React Native의 상위 구성 요소에있는 하위 구성 요소 값 (ListView에서)에 액세스하는 방법

Screenshot

내 하위 구성 요소의 모든 클릭은 내 부모 구성 요소에서 자신의 가치에 액세스 할 수있는 방법을, 나는이 개 하위 항목을 선택 위의 이미지에서 상태 값

{ selected: !this.state.selected } 

의 변화를 유발? 이건 내 자식 요소입니다 Hosted on Github too

import InterestItem from './InterestItem'; 

class AddInterest extends Component { 

    componentWillMount() { 
    this.createDataSource(this.props); 
    } 

    componentWillReceiveProps(nextProps) { 
    this.createDataSource(nextProps); 
    } 

    createDataSource({ items }) { 
    const ds = new ListView.DataSource({ 
     rowHasChanged: (r1, r2) => r1 !== r2 
    }); 
    this.dataSource = ds.cloneWithRows(items); 
    } 

    //return arrays of event from events 
    renderRow(item) { 
    return <InterestItem item={item} icon={computer} />; 
    } 

    render() { 
    const { centerEverything, skeleton, container, textContainer, contentContainer, listViewContainer, 
     titleContainer, descContainer, title, desc, submitContainer, submitTitle } = styles; 
    return (
     <View style={[container]}> 
     <View style={[centerEverything, textContainer]}> 
      <View style={titleContainer}> 
      <Text style={[title]}>What kind of events are you interest in?</Text> 
      </View> 
      <View style={descContainer}> 
      <Text style={[desc]}>You'll see more events from the categories you choose.</Text> 
      </View> 
     </View> 

     <View style={[contentContainer]}> 
      <ListView 
      enableEmptySections 
      contentContainerStyle={listViewContainer} 
      dataSource={this.dataSource} 
      renderRow={this.renderRow} 
      /> 
     </View> 

     <View style={[centerEverything, {paddingBottom: 10}]}> 
      <View style={[centerEverything, submitContainer]}> 
      <Text style={submitTitle}>Submit</Text> 
      </View> 
     </View> 

     </View> 
    ) 
    } 
} 

이 내 부모 조각입니다

Big Data: true 
IoT: true 

예를 들어

,,, @freesoul의 요청에 따라 Hosted on GitHub too

class InterestItem extends Component { 

    state = { 
    selected: false 
    } 

    render() { 
    const { skeleton, centerEverything, container, textStyle } = styles; 
    return(
     <TouchableWithoutFeedback onPress={() => this.setState({ selected: !this.state.selected })}> 
     <View style={[centerEverything, container, { backgroundColor: this.state.selected ? '#635eb4' : '#e7e7e7'}]}> 
      {this.props.icon} 
      <Text style={textStyle}>{this.props.item[0]}</Text> 
     </View> 
     </TouchableWithoutFeedback> 
    ) 
    } 
} 

, 여기 있어요 자식 인스턴스 (8 명의 자식이 있다고 생각할 때),363,210 enter image description here

+0

'InterestItem'의 단일 인스턴스를 고려해보십시오.'this.props.item'의 값은 무엇입니까? 예제를 게시 할 수 있습니까? –

+0

@ free-soul 요청한 정보를 추가했습니다. –

+2

내 제안은 부모님의 자녀 상태를 유지해야한다는 것입니다. 'state = {cars : false, bigData : true, hackintosh : false, iot : true, ...} '와 같은 것입니다. –

답변

2

@ 무료 - 영혼에 위로 따라, 당신의 코드에 다음과 같은 수정을 할 것입니다 : 다음

constructor(){ 
    this.state = { 
    //... 
     rowStates: {} // Holds the state for each row, identified by the uid property (I'm assuming it is unique, otherwise use some other value) 
    } 
    this.renderRow = this.renderRow.bind(this); 
    this.rowUpdated = this.rowUpdated.bind(this); 
} 
renderRow(item) { 
    // Adds a callback so that we know when an element has been pressed 
    return <InterestItem item={item} icon={computer} onPress={() => this.rowUpdated(item)}/>; 
} 

rowUpdated(item){ 
    let rowStates = {...this.state.rowStates}; // Make a copy of the object 
    rowStates[item.uid] = !rowStates[item.uid]; // If the item is not in the object, !undefined will be evaluated, which results in true, so the operation is safe 
    this.setState({rowStates}); 
} 

을, 자녀의 구성 요소는 다음과 같아야합니다

class InterestItem extends Component { 

    state = { 
    selected: false 
    } 

    render() { 
    const { skeleton, centerEverything, container, textStyle } = styles; 
    return(
     <TouchableWithoutFeedback onPress={() => {this.setState({ selected: !this.state.selected }); if(this.props.onPress) this.props.onPress(this.props.item)}}> 
     <View style={[centerEverything, container, { backgroundColor: this.state.selected ? '#635eb4' : '#e7e7e7'}]}> 
      {this.props.icon} 
      <Text style={textStyle}>{this.props.item[0]}</Text> 
     </View> 
     </TouchableWithoutFeedback> 
    ) 
    } 
} 

그것을 희망 help

+0

rowStates = {}이 (가) 유효하지 않습니다. 런타임시 오류에 대해 네이티브가 반응합니다. 상태를 null로 설정할 수 없습니까? –

+0

답변을 주셔서 감사합니다. 2 가지 실수가 있지만 도움이되었습니다. rowStates : {} 및 renderRow onPress 메서드 내부에서 우리는 굵은 화살표 함수로 반환해야합니다. onPress = {() => rowUpdated (item)} 그렇지 않으면 앱에서 자동으로 메서드를 실행합니다. –

+1

어, 죄송합니다! 쓰는 것을주의하지 않았다. 실수를 바로 잡기위한 답을 편집했습니다. – martinarroyo

관련 문제