首页 文章

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

提问于
浏览
2

我有一个组件添加todos AddTodo 工作正常,并用我添加的待办事项更新状态,我有一个组件 TodoItems 来显示 <FlatList/> 中的待办事项 . 我正在使用React Native Tab Navigator在组件之间切换,但我不确定如何将状态 this.state.todosAddTodo 组件发送到 TodoItems 组件 .

我一直在研究,但在Tab Navigator中找不到解决方案,但Stack Navigator有很多解决方案 .


Component 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>
        );
    }

}

Component 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>
        );
    }

}

Component Tabs

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 回答

  • 3

    嗯,我认为你有两个选择:

    • 您可以使用Redux,它允许您全局化您的状态对象,以便您可以在整个应用程序中使用它们,但它可能相当复杂https://redux.js.org/

    • 或者您可以在AddTodo中渲染TodoItems:

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

    然后你可以从TodoItems中访问这些数据:希望这会有所帮助!

相关问题