首页 > 解决方案 > 使用 setParams 和 getParam 将 state 的值传递给其他组件

问题描述

我使用componentWillMount()是因为我认为不可能将staticsetParams 与GalleryScreen.navigationOptions = navData => {}stateclass以及React.Component.

我一直在尝试使用这种方法,但我总是得到以下错误:

TypeError: undefined is not an object (评估'props.navigation.state.params.imageData')

我的结果是将 GalleryScreen.js 的值传递state.pickedImage给返回语句中的 EventInput.js。

GalleyScreen.js :这是 React 组件

 componentWillMount() {
    const {setParams} = this.props.navigation;
    setParams({imageData: this.state.pickedImage})
}

EventInput.js :这只是 EventInput 道具(不是 React 组件)

const EventInput = props => {
const [titleValue, setTitleValue] = useState('');
const [descriptionValue, setDescriptionValue] = useState('');

// const imageData = props.navigation.getParam('imageData');

const events = useSelector(state => state.events.events);

const titleChangeHandler = (title) => {
    setTitleValue(title);
};

const descriptionChangeHandler = (description) => {
    setDescriptionValue(description);
};

return (
    <View style={styles.container}>
        <StatusBar backgroundColor='transparent' translucent barStyle='dark-content'/>
        <Text>Event Input</Text>
        <TextInput 
            placeholder="Enter title..."
            onChangeText={titleChangeHandler}
        />
        <TextInput 
            placeholder="Enter description..."
            onChangeText={descriptionChangeHandler}
        />
        <Image source={{uri: props.navigation.state.params.imageData}} style={{width: 300, height: 300}}/>
        <TouchableOpacity onPress={() => {
            props.navigation.navigate('SetEventLocation', {
                eventTitle: titleValue,
                eventDescription: descriptionValue
            })
        }}>
            <Text>Next</Text>
        </TouchableOpacity>
    </View>
);
};

export default withNavigation(EventInput);

有没有其他解决方案,所以我可以传递我的价值state.pickedImage?并用于getParam从其他组件获取它的价值?

标签: reactjsreact-nativereact-navigation

解决方案


如果你想访问导航,你应该用“withNavigation”包装你的组件。

更多细节在这里


推荐阅读