在renderItem中传递Navigator对象

时间:2019-01-14 19:37:53

标签: react-native react-navigation

我正在努力使Navigator对象在List组件中可见。 这里的代码解释了:正如您在RootDrawer中所见,我有Concept组件。它仅显示基于id中传递的param的项目列表。 每个项目都指向另一个具有另一个ID的Concept,但我得到了

undefined is not an object (evaluating 'navigation.navigate')

当我用<RippleButton>按下那个onPress={() => navigation.navigate('Concept',{id:12})时。这里的问题是我没有正确传递Navigation对象。我该怎么解决?

主导航器抽屉

const RootDrawer = DrawerNavigator(
    {

        Home: {
            screen: StackNavigator({
                Home: { screen: Home }
            })
        },
        Search: {
            screen: StackNavigator({
                Cerca: { screen: Search },
                Concept: { screen: Concept },
            })
        }
    }
);

概念组件

export default class Concept extends Component {

    loading = true
    static navigationOptions = ({ navigation,state }) => ({
        headerTitle: "",
        title: `${navigation.state.params.title}` || "",
    })
    constructor(props) {
        super(props);
    }
    async componentDidMount(){
    }

    render() {
        const { params } = this.props.navigation.state;
        const id = params ? params.id : null;
        const { t, i18n, navigation } = this.props;
        const Concept = DB.get(id)


        return (
            <View>
                <ScrollView>
                    <List data={Concept.array|| []} title={"MyTile"} navigation={navigation} />
                </ScrollView>
            </View>
        );
    }

}

列表组件

class List extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        const { navigation } = this.props;
    }
    _renderItem = (item,navigation) => (
        <RippleButton
            id={item.id}
            onPress={() => navigation.navigate('Concept', { id: 12, otherParam: 'anything you want here'})}> //this line throws the error
            <Text>{item.Term}</Text>

        </RippleButton>

    )

    render() {
        const { navigation } = this.props;
        return (
            <View>
                <FlatList
                    data={this.props.data}
                    renderItem={({item}) => this._renderItem(item, navigation)}
                />
            </View>)
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用withNavigation HOC,而不是通过导航道具。

定义列表组件的位置

import { withNavigation } from 'react-navigation`

....


export default withNavigation(List)

现在,列表组件将可以访问navigation道具