reactnative传递导航到subView

时间:2017-07-21 14:05:50

标签: javascript react-native

我是反应迟钝的新手

我正在FlatList使用app.js并使用StackNavigator在以下场景之间导航:

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Content',
  };


  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
      <FlatList
        data = {myData}
          renderItem={({item}) => 
                            <Text style={styles.someStyle} 
                                  onPress={()=>
                                            navigate("Detail", 
                                                     {item: item});}>
                             {item.text}</Text> 
                      }
      />        
      </View>
    );
  }
}

上面的代码可以正常工作:当我按下其中一个列出的项目时,会加载另一个场景来显示项目内容的详细信息。

但是因为我想要列出项目的复杂样式,我认为在子视图中定义列出的项目会很方便,如下所示:

class MyHomeListItem extends React.PureComponent {
    render(){
        return (
          <View style={styles.item}>
              <Image
                source={require('./assets/book.png')}
                style={styles.listImageIcon}
              />
              // as you can see the following `onPress` was intended for 
              // the same poperse which should load another secene to show the detail.
              <Text onPress={()=>
                              {this.props.ref("Detail", 
                                               {item: this.props.item});}} 
                    style={styles.listItemHomeText}>

                    {this.props.chapterName}: {this.props.chapterTitle}
              </Text>
          </View>
        );
    }
}

我希望将FlatList中的数据作为属性传递:

 <FlatList
    data = {myData}

      renderItem={({item}) => <MyHomeListItem  chapterName={item.chapterName} chapterTitle={item.chapterTitle} ref={navigate} /> }
  />

如果我没有将navigate函数传递给subView,那么事情就行不通了,我认为没问题,所以我通过ref传递了它,这是{{1}的引用1}}函数(我认为)或仅通过navigate并在子视图中使用ref={this},但要么不起作用。

它将显示:

this.props.ref.navigate(...)

enter image description here

那我怎么能这样做?

更进一步,我实际上希望整个subView听取_this3.props.ref is not a function....'_this3.props.ref' is undefined ,但我找不到onPress

onPress属性

1 个答案:

答案 0 :(得分:1)

我相信ref是一个保留的prop,用于将子组件分配给父组件的ref,以便父组件可以轻松引用子组件。 尝试直接通过navigation={navigate}

传递它

此外,如果您希望整个onPress View,请尝试将View包裹在其中一个Touchable中,即TouchableHighlight,{ {1}}或TouchableOpacity。并将TouchableWithoutFeedback函数作为道具传递给onPress组件。

另外,就个人而言,我更喜欢在HomePage中定义Touchable逻辑,而item组件中的navigation函数只会通过{{1}传回该行的相应对象。从HomeScreen组件向下传递的prop。 这样,导航逻辑并不是所有地方,并且行项目组件可以是通用的,onPress函数将始终只传回相应的对象。

相关问题