导航 - 将变量传递给其他文件

Navigation - Pass variable to other files

我是 React-Native 的新手,这是我的第一个 React-Native 应用程序。但是,我已经遇到了一些问题。

我想将变量从一个 class (Home.js) 传递到另一个。 (是否可以在 render() 函数中不使用组件?)

##### Home.js #####
class Home extends Component {
constructor(props) {
    super(props);
    this.state = {direction: "defaultvalue"};  
  }

  getCurrentDirection() {
        return this.state.direction;
    }

  render() {
  /***..... some elements ..*/
    }
}
export default Home

#### Two.js ####
import Home from './Home'

/** SOME CODE **/    

const DrawerOptions = {
  initialRouteName: Home.getCurrentDirection(),
  contentComponent: CustomDrawerContentComponent,  
  drawerWidth: 300,
}; 

然而它不起作用...如何解决它?我已经尝试了一些解决方案,将 getCurrentDirection 声明为静态但什么也没有。

此外,这似乎是一个特定的案例,因为 DrawerOptions 不是 class。能否请您也添加到您的回复中,如果我想将变量获取到 class Two.js 中,该怎么做? 我的意思是如果 Two.js 例如:

 ##### Two.js #####
    class Two extends Component {
    var myvariable = Home.getCurrentDirection();

      render() {
      /***..... some elements ..*/
        }
    }

非常感谢

将状态从一个组件访问到另一个的推荐方法是使用(在本例中)Home 组件作为 Two 组件的父级。这样您就不必触发函数来访问 Home 的状态。每次更新父组件(在本例中)的状态时,Two 组件将收到更新后的 属性(方向)。如果你想从 Two 组件调用一个函数,你必须将一个函数作为 属性 (changeCurrentDirection) 传递给它,它将回调你想要的函数从 Home 组件触发。

所以你会得到这样的东西:

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      direction: "defaultValue"
    };
  }

  changeCurrentDirection() {
    this.setState({
      direction: "valueChanged"
    })
  }

  render() {
    let state = this.state;

    return (
      <Two 
        direction={state.direction}
        changeCurrentDirection={() => this.changeCurrentDirection.bind(this)}/>
    )
  }
}

class Two extends React.Component {
  render() {
    let props = this.props;
    
    return (
      <div>
        <h3>{props.direction}</h3>
        <button onClick={props.changeCurrentDirection()}>Change value</button>
      </div>
    )
  }
}


React.render(<Home/> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="app"></div>

您可以找到其他信息 here

此外,如果您想对组件的状态进行良好的管理,我建议您使用 redux。使用此库,您可以轻松连接组件的操作和属性,这些操作和属性可以进一步从您可以管理它们的其他文件访问。