[英]send child component's state to another component as props via tab navigator in react native
[英]React Native: Send component state to other component using Tab Navigator
我有一個添加待辦事項的組件AddTodo可以正常工作,並用添加的待辦事項更新狀態,並且我有一個組件TodoItems在<FlatList/>
顯示<FlatList/>
。 我正在使用React Native Tab Navigator在組件之間切換,但是我不確定如何將狀態this.state.todos
從AddTodo組件發送到TodoItems組件。
我一直在研究,但是在Tab Navigator中找不到解決方案,但是Stack Navigator有很多解決方案。
組件AddTodo
export default class AddTodo extends Component {
constructor(props) {
super(props);
this.state = {
todoText: null,
todos: []
}
}
onAdd = () => {
if (this.state.todoText) {
this.state.todos.push({'todoItem': this.state.todoText});
this.setState({todos: this.state.todos});
}
}
render() {
return(
<View>
<TextInput onChangeText={(text) => {
this.setState({todoText: text});
}} />
<TouchableOpacity onPress={() => {
this.onAdd;
}}>
</View>
);
}
}
組件TodoItems
export default class TodoItems extends Component {
constructor(props) {
super(props);
this.state = {
todosList: []
}
}
render() {
return(
<View>
<FlatList
data={this.state.todosList}
renderItem={(item, index) => {
<Text>{item.todoItem}</Text>
}}
/>
</View>
);
}
}
組件標簽
import {TabNavigator} from 'react-navigation';
import AddTodo from "./AddTodo";
import TodoItems from "./TodoItems";
var myTabs = TabNavigator(
{
'AddTodo':{screen: AddTodo,},
'TodoItems':{screen: TodoItems, },
},
{
tabBarPosition: 'top',
swipeEnabled: false,
tabBarOptions: {
labelStyle:{
fontSize: 13,
fontWeight: 'bold',
},
indicatorStyle: {
borderBottomColor: '#003E7D',
borderBottomWidth: 2,
},
style:{
backgroundColor: '#F30076',
elevation: 0,
},
},
});
export default myTabs;
好吧,我認為您有兩種選擇:
或者,您可以在AddTodo中渲染TodoItems:
render() { return( <View> <TextInput onChangeText={(text) => { this.setState({todoText: text}); }} /> <TouchableOpacity onPress={() => { this.onAdd; }}> </View> <TodoItems data={this.state.todos} /> ); }
然后,您可以從TodoItems中訪問該數據:希望這會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.