子组件值到父组件显示React Native

时间:2019-06-14 01:55:39

标签: javascript reactjs react-native

我有两个组成部分子组成部分父组成部分,该子组成部分的作用是给星级评分,现在我想获得来自子项的值以显示在父组件中,并使用来自子项的数据。

添加:我使用Redux并响应导航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);

1 个答案:

答案 0 :(得分:4)

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

父母:

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

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

孩子:

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

this.props.handleChange("your data")