React Native:使用Tab Navigator将组件状态发送到其他组件



我有一个要添加todos addtodo 的组件,它可以正常工作,并用我添加的todos更新状态,我有一个component todoitems >在<FlatList/>中显示招待员。我正在使用React Native Tab Navigator在组件之间切换,但我不确定如何从 aiddtodo 组件发送状态this.state.todos todoitems component。

我一直在研究,但找不到Tab Navigator中的解决方案,但是有很多用于堆栈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中渲染待办事项:

    render() {
      return(
         <View>
              <TextInput onChangeText={(text) => {
                   this.setState({todoText: text});
              }} />
              <TouchableOpacity onPress={() => {
                   this.onAdd;
              }}>
         </View>
         <TodoItems data={this.state.todos} />
      );
    }
    

然后,您可以从待办事项内访问该数据:希望这会有所帮助!

最新更新