首页 > 解决方案 > 子组件值到父组件显示 React Native

问题描述

我有两个组件子组件父组件,这个子组件的作用是星级,现在我想从子组件中获取值显示在父组件中并使用子组件的数据。

补充:我使用 Redux 和 react navigation 2.0

子组件

import React, { Component } from 'react';
//import react in our code. 
import {
  StyleSheet,
  View,
  Platform,
  Text,
  Image,
  TouchableOpacity,
} from 'react-native';


class Rate extends Component {
  constructor() {
    super();
    this.state = {
      Default_Rating: 0,
      //To set the default Star Selected
      Max_Rating: 5,
      //To set the max number of Stars
    };
    //Filled Star. You can also give the path from local
    this.Star = '../../assets/star_filled.png';
    //Empty Star. You can also give the path from local
    this.Star_With_Border = '../../assets/star_corner.png';
  }
  UpdateRating(key) {
    this.setState({ Default_Rating: key });
    //Keeping the Rating Selected in state
    this.props.onStarRating(this.state.Default_Rating)
  }

  render() {
    let React_Native_Rating_Bar = [];
    //Array to hold the filled or empty Stars
    for (var i = 1; i <= this.state.Max_Rating; i++) {
      React_Native_Rating_Bar.push(
        <TouchableOpacity
          activeOpacity={0.7}
          key={i}
          onPress={this.UpdateRating.bind(this, i)}>
          <Image
            style={styles.StarImage}
            source={
              i <= this.state.Default_Rating
                ?
                require('../../assets/star_filled.png')
                : require('../../assets/star_corner.png')
            }
          />
        </TouchableOpacity>
      );
    }
    return (
      <View style={styles.MainContainer}>
        {/*View to hold our Stars*/}
        <View style={styles.childView}>{React_Native_Rating_Bar}</View>
        <Text style={styles.textStyle}>
          {/*To show the rating selected*/}
          {this.state.Default_Rating} / {this.state.Max_Rating}
        </Text>
      </View>
    );
  }
}

export default Rate;

对于父组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container} from 'native-base';
import Rate from '../components/Rate'


class Leads extends Component {
  constructor(props) {
    super(props);

    this.state = {

    }
  }

  //RENDER MAIN COMPONENT
  render() {

    return (
      /* MAIN VIEW COMPONENT */
      <Container>
          <Rate  />
      </Container>
    )
  }
}

const mapStateToProps = (state) => ({

})
export default connect(mapStateToProps)(Leads);

标签: javascriptreactjsreact-native

解决方案


要从子组件获取数据到父组件,您可以将函数从父组件传递到子组件。然后一旦从子组件调用该函数,您就可以更新父组件中的数据。

家长:

handleChange = data =>{
   this.setState({ data: data })
}

render(){
   return(
      <Child
         handleChange={this.handleChange}
      >
   )
}

孩子:

在这里,您可以从父级调用该解析函数

this.props.handleChange("your data")

推荐阅读