gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:01:20 28 4
gpt4 key购买 nike

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

添加:我使用 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}
>
)
}

child :

在这里你可以从父级调用解析后的函数

this.props.handleChange("your data")

关于javascript - 子组件值到父组件显示React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56590485/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com