javascript - 在子组件和父组件之间进行通信以在反应原生中更改父组件中的视图内容的正确方法是什么?
问题描述
我有一个子组件,其中有一个按钮。
现在,我将其中三个子组件彼此相邻放置在一个父组件中。
每当触及这些子组件中的任何一个时,我都希望更改父组件中的内容。因此,每当单击按钮时,我希望更改父级中的状态(或任何方式),然后继续更改列表。我正在加载父级中使用的另一个子组件。但是当我按下这些按钮时,我的应用程序每次点击 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>
);
}
}
有什么我做错了还是不是反应方式?(这是我的第一个反应项目)
我有时也会Possible EventEmitter memory leak detected
在我的地铁捆绑器中收到警告。当我检查控制台时,我看到每次点击都会重新渲染一切,也许这让它变得如此缓慢以至于它最终放弃了?
解决方案
每件事看起来都不错,但是如果您为 child 添加默认道具,它将变得对其他开发人员更具可读性。
推荐阅读
- php - Symfony 4 - 如果队列不存在,如何创建队列
- coq - 在 Coq 中定义一个参数化的 Fixpoint
- c# - 在 Azure Pipeline 中使用 GlobalSuppressions.cs i StyleCop Runner
- javascript - Vuejs:即使删除令牌后也可以访问路由
- delphi - 截至 2018 年 11 月 1 日,谷歌街景 javascript api 显示灰屏
- java - 如何使用 java ftpclient 在远程位置上传重复文件
- orientdb - Gremlin 查询以检索 OrientDB 通用类的节点
- asp.net-mvc - 路由器提供程序 MVC
- javascript - 当我尝试从 jquery 将数据传递到 Flask 端点时没有响应
- azure - Microsoft Azure AD Graph API:获取按比例分配的用户许可证信息