如何在类之间传递变量

时间:2018-10-18 03:51:09

标签: javascript reactjs

好的,所以我正在尝试简化一个正在处理的项目,但是在互联网上阅读的所有信息中,没有一个可以回答我的问题。我的疑问是如何将变量(变量的名称及其值)从一个类传递到另一类?我应该使用道具吗?我是否应该做类似this.state.variable的事情?怎么做到呢?我将编写示例代码只是为了更直观地显示我想做的事情,但是,这不是我的实际代码。感谢您的帮助:)

class FishInSea{
    constructor(props){
        super(props);
        this.setState({fishInSea: 100});
    }
    render(){
        return(
            <div>Fish in the sea: {this.state.fishInSea}</div>
        );
    }
}

class FishInOcean{
    constructor(props){
        super(props);
        this.setState({fishInOcean: <FishInSea this.props.fishInSea/> * 1000});
    }
    render(){
        return(
            <div>Fish in the ocean: {this.state.fishInOcean}</div>
        );
    }
}

export default FishInOcean;

1 个答案:

答案 0 :(得分:2)

您首先需要将这两个类都放入React组件中。由于这两个类都修改状态,因此它们被称为有状态组件。该类必须扩展React的基础类,即Component。

在构造函数中,我们仅进行状态初始化,而不修改那里的状态。但是您修改的状态不正确。而是将setState移到componentDidMount。

假设在FishInSea类中您有fishInSea,并且您想将其作为道具传递给FishInOcean组件。

检查以下两个更正的组件如何将它们从一个组件传递到另一个组件

  import React, { Component } from “react”;
  class FishInSea extends Component{
       constructor(props){
            super(props);
            this.state = {
                 fishInSea: 100
            }
       }
       componentDidMount(){
             this.setState({fishInSea: 100});
       }
       render(){
           const { fishInSea } = this.state;
                return(
                   <div>Fish in the sea: 
                         <FishInOcean fishInSea={fishInSea} />
                   </div>
            );
        }
   }


    import React, { Component } from “react”;
    class FishInOcean extends Component{
         constructor(props){
             super(props);
             this.state = {fishInOcean: 1000}
         }
         componentDidMount(){
             this.setState({fishInOcean: 1000});
          }
        render(){
           const { fishInOcean} = this.state;
           const { fishInSea } = this.props;
           return(
               <div>Fish in the ocean: {fishInOcean}
                    {fishInSea}
               </div>
           );
       }
   }

  export default FishInOcean;
  /*There was a typo*/
相关问题