简体   繁体   中英

Passing function as props in Reactjs

I am trying to pass function as prop. I did this before but now with the same logic it is giving me error (this.props.functionName is not a function). I have a child (Navbar) and a parent component(MainComponent). I want to send a input value from Navbar to MainComponet and set it to the state value in parent Component.

Parent Component

    import React ,{Component}from 'react'
    import Navbar from '../Presentational/Navbar'

class Main extends Component{
constructor(props){
    super(props)
    this.state = {
        searchItem: ''
    }
}

GetSearchItem(search){
    this.setState({searchItem:search})
}
render(){
    return(
        <div className = 'container'>
            <div className = 'row'>
                <div className = 'col-12 mt-1'>
                    <Navbar onChange = {(search)=>this.GetSearchItem(search)}></Navbar>
                </div>
            </div>
            <div className = 'row'>
                <div className = 'col-3'>
                    <h3>{this.state.searchItem}</h3>
                </div>
            </div>
        </div>
    )
}
}

export default Main

Child Component (Navbar)

import React,{Component} from 'react'
import {AppBar,Toolbar,IconButton,Typography,InputBase} from '@material-ui/core'
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import {fade , makeStyles} from '@material-ui/core/styles'

const useStyles = makeStyles((theme) => ({
root: {
  flexGrow: 1,
},
menuButton: {
  marginRight: theme.spacing(2),
},
title: {
  flexGrow: 1,
  display: 'none',
  [theme.breakpoints.up('sm')]: {
    display: 'block',
  },
},
search: {
  position: 'relative',
  borderRadius: theme.shape.borderRadius,
  backgroundColor: fade(theme.palette.common.white, 0.15),
  '&:hover': {
    backgroundColor: fade(theme.palette.common.white, 0.25),
  },
  marginLeft: 0,
  width: '100%',
  [theme.breakpoints.up('sm')]: {
    marginLeft: theme.spacing(1),
    width: 'auto',
  },
},
searchIcon: {
  padding: theme.spacing(0, 2),
  height: '100%',
  position: 'absolute',
  pointerEvents: 'none',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
},
inputRoot: {
  color: 'inherit',
},
inputInput: {
  padding: theme.spacing(1, 1, 1, 0),
  // vertical padding + font size from searchIcon
  paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
  transition: theme.transitions.create('width'),
  width: '100%',
  [theme.breakpoints.up('sm')]: {
    width: '12ch',
    '&:focus': {
      width: '20ch',
    },
  },
},
 }));

class Navbar extends Component{

render(){
    const classes  = this.props.classes;;
    return(
        <div className={classes.root}>
            <AppBar position="static">
                <Toolbar>
                    <IconButton
                        edge="start"
                        className={classes.menuButton}
                        color="inherit"
                        aria-label="open drawer"
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography className={classes.title} variant="h6" noWrap>
                        Pizaa Valley
                    </Typography>
                    <div className={classes.search}>
                        <div className={classes.searchIcon}>
                        <SearchIcon />
                        </div>
                        <InputBase
                        placeholder="Search…"
                        classes={{
                            root: classes.inputRoot,
                            input: classes.inputInput,
                        }}
                        inputProps={{ 'aria-label': 'search' }}
                        onChange={(event)=>this.props.onChange(event.target.value)}
                        />
                    </div>
                </Toolbar>
            </AppBar>
        </div>
    )
}
}


export default () => {
const classes = useStyles();
return (
    <Navbar classes={classes} />
)
}

The problem is that you have two Navbar types. You first have the class component created using class Navbar . And second you have the following functional component defined here:

export default () => {
const classes = useStyles();
return (
    <Navbar classes={classes} />
)
}

When you do

import Navbar from '../Presentational/Navbar'

<Navbar onChange = {(search)=>this.GetSearchItem(search)}></Navbar>

The onChange prop is correctly given to the functional component, but is never passed along to the class-based component. You can fix this by replacing your functional component with the below code:

export default props => {
    const classes = useStyles();
    return (
        // using the "spread operator", we pass along all the props given
        // to the functional component, so the class-based component can 
        // also access these
        <Navbar {...props} classes={classes} />
    )
}

you've done everything correctly except change this:

GetSearchItem(search){
    this.setState({searchItem:search})
}

to

GetSearchItem = (search) => {
    this.setState({searchItem:search})
}

as an arrow function it has access to the scope above

Try with the following:-

In your parent component modified the below line:-

  <Navbar onChangeCallBack = {(search)=>this.GetSearchItem(search)}></Navbar>

In your child Navbar component only modified the below line:-

  onChange={(event)=>this.props.onChangeCallBack(event.target.value)}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM