javascript - 子组件值到父组件显示 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);
解决方案
要从子组件获取数据到父组件,您可以将函数从父组件传递到子组件。然后一旦从子组件调用该函数,您就可以更新父组件中的数据。
家长:
handleChange = data =>{
this.setState({ data: data })
}
render(){
return(
<Child
handleChange={this.handleChange}
>
)
}
孩子:
在这里,您可以从父级调用该解析函数
this.props.handleChange("your data")
推荐阅读
- jquery - 如何使用 jquery“Ajax”工具提示显示 laravel 雄辩的数据?
- apache-kafka-streams - 使用 Kafka 2.2.x 的 Spring 嵌入式 Kafka
- asp.net-mvc - 如何使用 Enum 创建单选按钮列表并将它们绑定到模型?
- sql - 更新表数据,从另一个表中获取
- java - 无法使用 vscode 运行 Java 程序
- dynamics-crm - Microsoft.OData.Client $expand 不填充模型
- python - 如何以特定的间隔将项目插入列表以匹配另一个列表的 len?
- html - 相同的 css 在草图和浏览器中出现不同
- c - 如何在C中的整数数组中添加二次序列
- javascript - 来自 http 错误代码的错误描述 - react.js/javascript