【发布时间】:2020-02-21 02:22:35
【问题描述】:
我正在尝试构建报告控制器,它根据子组件的 state.reports 路由到详细组件
我的概念是这样的
1 - render the top level of array
2 - each array element is clickable and call function **route**
- if element has children set state to child array and go to step 1
- else go to detail page
3 - if we are at child array we show **back button** that can return to previous render.
这是我的控制器
export default class ReportControler extends React.Component {
state = {reports: [] }
componentWillMount() {
this.parent = null;
this.path = [this.constructor.name];
}
route = (report) =>{
if(report.children) return this.moveToChild(report);
this.props.navigation.navigate('ReportDetails', this.path.join('/') + '/' + report.title);
}
moveToChild = (report) => {
this.parent = this.state.reports;
this.path.push(report.title);
this.setState({reports: report.children});
}
moveToParent = () => {
this.setState({reports: this.parent});
this.parent = null;
this.path.pop();
}
render(){
const reports = this.state.reports.map(report => (
<TouchableWithoutFeedback onPress={() => { this.route(report) }} >
<View><Box title={report.title} image={report.image} /></View>
</TouchableWithoutFeedback >
));
let back = null;
if(this.parent){
back = <TouchableWithoutFeedback onPress={this.moveToParent} >
<View>
<Text style={{color: '#274496', fontSize: 20, padding: 10, borderBottom: '#274496', borderBottomWidth: 2 }}>{this.path.join(' / ') }</Text>
</View>
</TouchableWithoutFeedback >
}
return(
<View style={{flex: 1}}>
{back}
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
{reports}
</View>
</View>
);
}
}
子组件会像这样工作
export default class Leads extends ReportController {
state = {reports: [
{title:"Campaign", image: require('../../assets/Report/bullhorn.png') },
{title:"Status", image: require('../../assets/Report/analysis.png') },
{title:"Source", image: require('../../assets/Report/wind-turbine.png') },
{title:"Location", image: require('../../assets/Report/route.png') },
{title:"Device", image: require('../../assets/Report/responsive.png') },
{
title:"Time", image: require('../../assets/Report/statistics.png'),
children: [
{title:"Days", image: require('../../assets/Report/statistics.png')},
{title:"Hours", image: require('../../assets/Report/statistics.png')},
]
},
]
}
}
我现在的问题是关于后退功能。
此功能不适用于 2 级以上
如何设置this.parent 数组?
moveToParent = () => {
this.setState({reports: this.parent});
this.parent = null; //Here I should set the parent array
this.path.pop();
}
【问题讨论】:
-
我没有代码示例,但有一个关于如何执行此操作的一般想法。如果您希望它适用于未知级别的父子关系,最好的方法是使其递归。尝试在 ReportControler 中使用 ReportControler。将数据作为 props 发送到 ReportControler,如果您获得的数据不是报表数组,则呈现图表,如果是数组,则再次将其传递给 ReportControler 内的 ReportControler。希望这是有道理的。
-
谢谢。我有同样的想法,但我仍然没有找到控制后退按钮的方法
-
如果你在url中维护状态,返回会更容易,你可以使用浏览器返回。
-
每个级别的每个 ReportControler 都应该维护一个标志并传递一个方法来将该标志从详细信息翻转到列表以及从列表到详细信息。
标签: javascript arrays json reactjs react-native