gpt4 book ai didi

javascript - 在 react native 中,子组件和父组件之间进行通信以更改父组件中的 View 内容的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 01:59:39 25 4
gpt4 key购买 nike

我有一个子组件,其中有一个按钮。

现在,我将三个子组件并排放置在一个父组件中。

每当触及这些子组件中的任何一个时,我都希望更改父组件中的内容。因此,每当单击按钮时,我希望更改父级中的状态(或任何方法),然后继续更改列表。我正在加载父组件中使用的另一个子组件。但是当我按下这些按钮时,我的应用程序每次点击 3-4 次后就会卡住。

我想也许我正在做一些非常基本的错误。就像使用错误的状态/属性并将应用程序发送到无限循环或其他什么。

父组件:

export default class Dash extends PureComponent {
constructor(){
super();
// Bind the this context to the handler function
this.state = {
activeAuctionsCount: 15,
wonAuctionsCount: 10,
convertedLeadsCount: 6,
isActiveAuctionsSelected: true,
iswonAuctionsSelected: false,
isconvertedLeadsSelected: false,
cardSelected: 'auctions', /* auctions/won/leads */
};
this.loadActiveAuctions = this.loadActiveAuctions.bind(this);
this.loadWonAuctions = this.loadWonAuctions.bind(this);
this.loadconvertedLeads = this.loadconvertedLeads.bind(this);
}

// This method will be sent to the child component
loadActiveAuctions() {
console.log('active pressed');
this.setState({
cardSelected: 'auctions'
});
}
loadWonAuctions() {
console.log('won pressed');
this.setState({
cardSelected: 'won'
});
}
loadconvertedLeads() {
console.log('leads pressed');
this.setState({
cardSelected: 'leads'
});
}

render() {
return (
<DealerShipDashStatsCard
statCardLayoutPath={statCardLeft}
statCardTitle={'NOW'+"\n"+'SHOWING'}
statValue={this.state.activeAuctionsCount}
isSelected={this.state.isActiveAuctionsSelected}
action={this.loadActiveAuctions}
/>
</View>

子组件:

export default class DealershipDash_StatsCard extends Component {
render() {
console.log("Rendering DashStat Card "+ this.props.statCardTitle);
return (
<ImageBackground
source={this.props.statCardLayoutPath}
style={styles.stat_card}
resizeMode="cover"
resizeMethod="resize">
<View style={styles.cardTop}></View>
<View style={styles.cardBottom}>
<View style={styles.cardStatTitle}>
<Text style={[styles.statTitleText]}>{this.props.statCardTitle}</Text>
</View>
<View style={styles.cardStatValue}>
<Text style={styles.cardStatValueText}>{this.props.statValue}</Text>
</View>
<View style={styles.cardButton}>
<Image
source={this.props.isSelected ? cardButtonActive : cardButtonInactive }
style = {this.props.isSelected ? styles.stat_card_button : styles.stat_card_button_inactive}/>
</View>
</View>
<Button onPress={this.props.action} title="press"/>
</ImageBackground>
);
}
}

我做错了什么或者 react 方式不对吗? (这是我的第一个 React 项目)

我有时还会在我的 Metro 捆绑程序中收到检测到可能的 EventEmitter 内存泄漏警告。当我检查控制台时,我看到每次点击都会重新渲染所有内容,也许这使得它变得如此缓慢以至于最终放弃?

最佳答案

一切看起来都不错,但如果您为 child 添加默认属性,其他开发人员将变得更具可读性。

关于javascript - 在 react native 中,子组件和父组件之间进行通信以更改父组件中的 View 内容的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719961/

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