So, I am having this problem with goBack function "Cannot read property of undefined" I want when I press An arrowBack icon it goes back to MainSettings COMPONENT
Parent component
const MainSettings=()=> {
const [isSystemOpen, setIsSystemOpen]= React.useState(false)
const {goBack} = this.props.navigation;
function openSystem(){
setIsSystemOpen(true)
}
function closeSystem(){
setIsSystemOpen(false)
}
return (
<div className="mainSettings">
<ComputerIcon onClick={openSystem} />
{isSystemOpen ? <System closeSystem={closeSystem} />: null}
</div>
Child Component
const System =(props)=> {
return (
<div className='mainSystem'>
<ArrowBackIcon className='arrow'onClick={this.props.navigation.goBack()}
There are a couple of problems with your code.
You are using this
in function components. There is no need to use this
in function components, so just use props
when you want to reach it.
For example, in your MainSettings
component, you are trying to get your props
with this.props.navigation
which you shouldn't. You can get it with:
const MainSettings = (props) => ...
and then use like:
const { goBack } = props.navigation;
You are not passing goBack
as a prop to your child component. So, you should do it:
<System closeSystem={closeSystem} goBack={goBack} />
You shouldn't invoke your goBack
function on your onClick
handler. You can use the reference:
<ArrowBackIcon className='arrow' onClick={props.navigation.goBack}
In your parent you need useHistory:
import { userHistory } from 'react-router-dom';
function MainSettings() {
const history = useHistory();
function historyGoBack() {
history.goBack();
}
...
Then you can use it in the child component from the parent:
<System closeSystem={closeSystem} back={this.historyGoBack()} />
The child component itself modifying your ArrowBackIcon:
...
<ArrowBackIcon className='arrow' onClick={this.props.back} />
Then clicking on the arrow should go back as you want it to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.