简体   繁体   English

React Native-setState到其他组件

[英]React Native - setState to other component

I would like to change some layout in Header when Home is started. 我想在启动Home时更改Header某些布局。 So I decide to call the setState when Home componentWillMount . 所以我决定在Home componentWillMount时调用setState How can I setState to other component in different js file. 如何将State设置为不同js文件中的其他组件。

Header.js Header.js

    class Header extends React.Component {
        constructor(props) {
            super(props);
            this.state = { type: '' };
        }

        render() {
            if(this.state.type == "home"){
                //do something
            }else{
                //do something
            }
         }
    }

    module.exports = Header;
    AppRegistry.registerComponent('myApp', () => Header);

Home.js Home.js

    class Home extends React.Component {

        //set from here
        componentWillMount(){
            this.setState({Header.state.type:'home'});
        }
    }

    module.exports = Home;
    AppRegistry.registerComponent('myApp', () => Home);

You need one common parent component and only one initial component mounting via AppRegistry.registerComponent() . 您需要一个公共父组件,并且只需要通过AppRegistry.registerComponent()安装一个初始组件。 Like so: 像这样:

Parent.js Parent.js

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { type: '' };
    }

    render() {
        <Header></Header>
        <Home></Home>
     }
}

module.exports = Parent;
AppRegistry.registerComponent('myApp', () => Parent);

The AppRegistry.registerComponent(); AppRegistry.registerComponent(); calls in your other components need to be removed. 您其他组件中的呼叫需要删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native:setState +已卸载或正在安装的组件 - React Native: setState + unmounted or mounting component 如何在不同的组件React Native中设置setState? - How to setState in different component React native? 来自子组件的SetState在React Native上失败 - SetState from Child Component fails on React Native 如何在本机反应中重用 function 和 this.setState 和其他组件 function? - How can I reuse a function with this.setState and other component function in react native? 将 SetState 从父组件传递给 React Native 中的子组件 - Pass SetState from parent component to a child component in React Native 如何避免警告:无法在未安装的组件上设置状态? 反应本机 - How to avoid warning: Cannot setState on unmounted component? REACT-NATIVE 无法在尚未安装的组件上调用 setState - 反应原生 - Can't call setState on a component that is not yet mounted - react native 在反应原生 class 组件中,不能不使用 setstate 更新 state - In react native class component , cant not use setstate to update state 如何使用条件 setState 并将该值赋予 React Native 中的另一个组件? - How to use conditional setState and give that value to another component in React Native? 如何从 React Native 中的另一个 class 组件设置状态? - How to setState from another class component in React Native?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM