在Reactjs中将函数作为道具传递

时间:2020-06-13 15:02:52

标签: javascript reactjs web material-ui

我正在尝试通过功能作为道具。我以前这样做过,但现在使用相同的逻辑给我错误(this.props.functionName不是函数)。 我有一个孩子(导航栏)和一个父组件(MainComponent)。我想从Navbar向MainComponet发送输入值,并将其设置为父组件中的状态值。

父组件

    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

子组件(导航栏)

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} />
)
}

3 个答案:

答案 0 :(得分:1)

问题是您有两种Navbar类型。首先,您需要使用class Navbar创建类组件。其次,您在此处定义了以下功能组件:

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

完成时

import Navbar from '../Presentational/Navbar'

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

onChange道具已正确地提供给功能组件,但从未传递给基于类的组件。您可以通过使用以下代码替换功能组件来解决此问题:

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} />
    )
}

答案 1 :(得分:0)

您已正确完成所有操作,但需要更改以下内容:

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

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

作为箭头功能,它可以访问上面的范围

答案 2 :(得分:0)

尝试以下操作:-

在您的父组件中修改了以下行:-

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

在您的子级Navbar组件中,仅修改了以下行:-

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