类型错误:无法读取未定义 React js 的属性“值”

时间:2021-04-29 07:14:18

标签: reactjs react-hooks material-ui

当我在搜索栏上搜索然后得到一个错误,比如无法读取属性值,为什么会出现这个错误,以前我做了很多表单但没有出现这个错误,请告诉我为什么会出现这个错误,我应该改用材料 UI Bootstrap 替换

<块引用>

Music.js

这是我出错的music.js文件,我使用react-hooks来管理状态

import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import RadioIcon from '@material-ui/icons/Radio';
import firebase from '../Firebase';
import SearchBar from "material-ui-search-bar";
import { useHistory } from 'react-router-dom';
import { Container, Input, TextField } from '@material-ui/core';



const useStyles = makeStyles((theme) => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
    },
    search:{
        marginTop:30,
    },
}));

const Music = () => {

    const [search, setSearch] = useState("");

    const history = useHistory();

    const Logout = () => {
        firebase.auth().signOut().then(() => {
            alert("Logout Successfull...");
            history.push('/');
        }).catch((error) => {
            console.log(error);
        });
    }

    const classes = useStyles();

    return (
        <div className={classes.root}>
                <AppBar position="static">
                    <Toolbar>
                        <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
                            <RadioIcon style={{ fontSize: "30px" }} />&nbsp; React Music
                    </IconButton>
                        <Typography variant="h6" className={classes.title}>
                        </Typography>
                        <Button color="inherit" onClick={Logout}> <ExitToAppIcon /> Logout </Button>
                    </Toolbar>
                </AppBar>
                <Container>
                    <SearchBar className={classes.search}
                    value={search}
                    onChange={(e)=>setSearch(e.target.value)}/>
                </Container>
                
        </div>
    );
}

export default Music;

2 个答案:

答案 0 :(得分:2)

按照 documentation 中的示例,onChange 只是将新值而不是事件作为参数。

您可以像这样修复您的代码:

onChange((newValue)=>setSearch(newValue))

答案 1 :(得分:2)

根据 documents onChange 方法返回 newValue,因此您应该将方法更改为:

<SearchBar className={classes.search}
 value={search}
 onChange={(newValue)=>setSearch(newValue)}/>