簡體   English   中英

獲取父組件中的子狀態組件值

[英]Get child state component value in parent component

我有kidsDetail組件,它有自己的狀態,在父kidsDetail組件中使用for循環渲染多個時間。 我想獲取詳細的孩子列表,單擊保存按鈕上的詳細信息。

波紋管是父組件代碼

     renderKidsDetails(totalkids) {
      /*If user selects 'yes' for kids, then this function is called 'n' 
      times; n = no. of kids */
      const kids= [];
      if (this.state.addKidsDetails === true) {
       for (let i = 0; i < totalkids; i++) {
      kids.push(
      <RenderChildDetails key={i} ivalue={i + 1} />
      );
      }

     }
     return (
        <View style={{ marginLeft: 20 }}>
         {kids}
        </View>
      );
      }

KidsDetail.js,它有兩個州孩子,分別是年齡和性別,因此需要在父組件中獲取此值

class RenderChildDetails extends Component {
 state={
   kidsAge: 0,
   kidsGender: '',
 }
constructor(props) {
   super(props);
   onClicked=this.onClicked;
 //Call function when the back button is pressed in the page header.
  }

onClicked=()=>{
 console.log(" kid Age  "+this.state.kidsAge);
}
render()
   {
    return(
     <View style={{flexDirection:'row',flex:1}}>
  <View style={{backgroundColor:'black',height:20,width:20,borderRadius:10,margin:5,alignItems:'center', padding: 1}}>
   <Text style={{color:'white'}}>{this.props.ivalue}</Text>
 </View>
 <TouchableOpacity onPress={() =>{

                         ActionSheet.show(
                           {
                             options: AGE,
                             cancelButtonIndex: CANCEL_INDEX,
                             destructiveButtonIndex: DESTRUCTIVE_INDEX,
                             title: "Select Age"
                           },
                           buttonIndex => {
                             this.setState({ kidsAge: AGE[buttonIndex] });
                           }
                         )

                       }
                       }>

  <View style={{flex:1,margin:5,flexDirection:'row'}} >
    <Text>Age: {this.state.kidsAge}</Text>
    <Image source={require('../../../Assets/Icons/Settings/Black_down.png')}
           style={{height:11,width:11,margin:5}} />
  </View>
  </TouchableOpacity>
  <TouchableOpacity onPress={() =>
      ActionSheet.show(
                        {
                          options: GENDER,
                          cancelButtonIndex: CANCEL_INDEX,
                          destructiveButtonIndex: DESTRUCTIVE_INDEX,
                          title: "Gender"
                        },
                        buttonIndex => {
                                        this.setState({ kidsGender: GENDER[buttonIndex] });
                                      }
                      )}>
  <View style={{flex:1,margin:5,flexDirection:'row'}}>
    <Text>Gender: {this.state.kidsGender}</Text>
    <Image source={require('../../../Assets/Icons/Settings/Black_down.png')}
           style={{height:11,width:11,margin:5}} />
  </View>
  </TouchableOpacity>
 </View>


 );

 }
 }

 export default RenderChildDetails;

在React中,只要子組件狀態被更新,您就可以簡單地將處理程序傳遞給子組件以進行調用,然后將子組件狀態存儲在父組件狀態中。

檢查以下代碼:

 class Parent extends Component {
     constructor(props) {
      super(props)
      this.state = {};
      this.handleChildUpdate = this.handleChildUpdate.bind(this);
      this.getChildState = this.getChildState.bind(this);
     }


     //handler to update current parent state when child state is updated
     handleChildUpdate(updatedState){
      this.setState({
        childState:updatedState
      });
     }

     //log updated child state on button click
     getChildState(){
      console.log(this.state.childState.age);
     }

     render(){
      <View >
        <Child handleUpdate={this.handleChildUpdate} />
        <Button onPress={this.getChildState}>
      </View>
     }
 }


 class Child extends Component {
     constructor(props) {
      super(props)
      this.updateAge = this.updateAge.bind(this);
      this.state = {
          age:"10"
      };
     }


     updateAge(text){
      this.setState({
        age:text
      } , () => {
        //this handler is passed as a prop from parent component
        //this is how we update the parent state when any change happens to child state
        this.props.handleUpdate(this.state);
      });
     }


     render(){
      <View >
        <TextInput onChange={(text) => { this.updateAge(text) } } />
      </View>
     }
 } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM