簡體   English   中英

React Native:使用Tab Navigator將組件狀態發送到其他組件

[英]React Native: Send component state to other component using Tab Navigator

我有一個添加待辦事項的組件AddTodo可以正常工作,並用添加的待辦事項更新狀態,並且我有一個組件TodoItems<FlatList/>顯示<FlatList/> 我正在使用React Native Tab Navigator在組件之間切換,但是我不確定如何將狀態this.state.todosAddTodo組件發送到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;

好吧,我認為您有兩種選擇:

  1. 您可以使用Redux,它允許您全球化狀態對象,以便可以在應用程序中使用它們,但是它可能相當復雜https://redux.js.org/
  2. 或者,您可以在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM