0
使用react-native,如何將父視圖,讀寫對象傳遞給子視圖,在哪裏可以修改,然後在子視圖返回父視圖時重新呈現父視圖?如何在react-native中將讀寫數據源項從父視圖傳遞給子視圖?
我在導航器中有一個WaypointList ListView。 當用戶選擇一行時,DetailView顯示TextInput進行編輯。
// The Parent "Master View"
var WaypointList = React.createClass({
getInitialState: function() {
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
return {
itemList: this._genRows(),
dataSource: ds.cloneWithRows(this._genRows()),
editEnabled: false,
planLocked: false,
selectionCount: 0,
unitType: 0,
};
},
// ToDo: Turn this into a real database datasource
_genRows: function(): Array <any> {
var arrayList = [];
var waypoint = new Waypoint('Waypoint1', 0.0, 0.0, 10, true);
arrayList.push(waypoint);
waypoint = new Waypoint('Waypoint2', 20.0, 4.0, 10, true);
arrayList.push(waypoint);
return arrayList;
},
getDataSource: function(waypoints: Array <any>): ListView.DataSource {
return this.state.dataSource.cloneWithRows(waypoints);
},
selectRow: function(waypoint: Object) {
this.props.navigator.push({
title: waypoint.name,
component: WaypointScreen,
passProps: {
waypoint: waypoint,
},
});
},
});
// The Child "Detail View"
// How can I modify an object passed into the "Detail View"
// passProps appears to be read-only ?
var DetailView = React.createClass({
textInputValue: null,
getInitialState: function() {
console.log('name:', this.props.person.name);
console.log('age:', this.props.person.age);
return {
textDistance: this.props.waypoint.distance.meters.toString(),
textDepth: this.props.waypoint.depth.meters.toString(),
};
},
render: function() {
return (< View style = {
{
flexDirection: 'row',
justifyContent: 'center'
}
} >
< TextInput style = {
styles.textInput
}
ref = 'distance1'
placeholder = "Enter meters"
editable = {
isEditable
}
keyboardType = "decimal-pad"
returnKeyType = 'next'
onChangeText = {
(text) => {
text = text.replace(/\D/g, '');
var meters = parseFloat(text);
this.setState({
textDistance: text
});
}
}
value = {
this.state.textDistance
}
onSubmitEditing = {
(event) => {
this.refs.depth1.focus();
}
}
/>
<View style={styles.separatorHorizontal}/>
< /View>
);
},
});
我開始學習反應本土大約兩週前然而,我沒有接近找出一個解決方案。
PassProps僅用於只讀信息嗎?
如何實現對數據源的讀寫修改?
在此先感謝。
任何提示或方向大加讚賞,
-Ed
非常感謝您的例子。我想了解如何在使用導航器時將onChange回調傳遞給孩子?我認爲這需要在我的selectRow方法中完成 –
不要緊,使用「passProps:{onChange:this.onChange}」傳遞迴調,並且子進程使用this.props.onChange(this.props.waypoint)進行回調;但是,我無法改變這個孩子的this.props.waypoint,因爲它是隻讀的。我是否需要爲每個路點對象字段創建一個回調方法,然後父母修改源路點對象,而不是通過路點對象的回調? –
我希望我真正需要了解的是應用程序爲了顯示和修改數據源而將數據源傳遞到多個視圖。這很快變得具有挑戰性。再次感謝你的幫助。 –