反应原生更新导航IOS组件的道具



我有以下代码,其中HomeTab包含NavigatorIOS。我正在传递HomeScreen作为导航器的组件。

我有一些事件发生在包含HomeTab的父组件上,并希望将它们传递给HomeScreen。我能够得到HomeTab。我如何设置组件的道具或状态,最好,我希望能够调用它的函数。有线索吗?

class HomeTab extends React.Component {
  constructor() {
    super()
    this.state = {}
  }
  render() {
    return (
        <NavigatorIOS style={styles.container}
            initialRoute={{
              title: 'Home',
              component: HomeScreen,
              passProps: {}
            }}
        />
    )
  }
}

您可以简单地通过那里的passProps对象传递它们。

我想你可能错过了你的主屏幕组件的另一部分。

var HomeScreen = React.createClass({
    propTypes: {
        text: React.PropTypes.string.isRequired,
    },

然后在你的根视图中你要做

class HomeTab extends React.Component {
  constructor() {
    super()
    this.state = {}
  }
  render() {
    return (
        <NavigatorIOS style={styles.container}
            initialRoute={{
              title: 'Home',
              component: HomeScreen,
              passProps: {text: 'Woot!'}
            }}
        />
    )
  }
}

注意:如果你提供了isRequired,那么当你显示/推主屏时,如果你不提供它,你的代码就会突然停止

是的,导航器模型破坏了React-y数据流(正如我在这个答案中概述的那样:从列表视图中保存数据的正确方法是什么?)

我认为实现你想要做的最好的方法是让这个地理位置服务提供一个全局订阅功能,你的HomeScreen组件订阅。例如,使用React Native自带的Geolocation模块的API:

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {locationInfo: {...}};
    this._watchID = Geolocation.watchPosition(
      (locationInfo) => {this.setState({locationInfo});},
      (error) => {...},
      ...
    );
  }
  componentWillUnmount() {
    Geolocation.clearWatch(this._watchID);
  }
  render() {
    ...
  }
}

如果你在设备API和应用程序之间使用某种自定义位置服务,那么我会为该服务建模一个类似的API。例如,你可以使用React Native自带的EventEmitter库。

现在,如果你绝对必须HomeTab中获得HomeScreen的实例,那么这也是可能的,使用ref prop,正如我在这个答案中概述的:

最新更新