React MenuItem event.target.value 不能在一个菜单项中工作,但适用于另一个 MenuItem

React MenuItem event.target.value not working in one, but works for the other MenuItem

我有两个 MenuItem 下拉菜单。第一个用于在两个项目之间进行选择(不工作),第二个下拉菜单有一个年份列表,这是工作的。

以下是我创建的用于为每个函数捕获 event.target.value 的函数:

 handleYrChange = (event) => {
    console.log('handleYrChange: ' + event.target.value);
    this.setState({ data: [] });
    getPartIdUpperSa(event.target.value).subscribe((res) => {
        this.setState({ data: res });
        this.setState({ isLoading: false });
    });
    this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
    this.setState({ yrValue: event.target.value });
    this.onCloseYr();
}

handleSaChange = (event) => {
    console.log('handleSaChange: ' + event.target.value);

    if(event.target.value === 'notSa') {
        this.setState({ isPartIdUpperSa: false });
    } else {
        this.setState({ isPartIdUpperSa: true });        
    }

    setBaseUrl(event.target.value);
    this.setState({ saValue: event.target.value });
    this.onCloseSa();
}

handleYrClick = (event) => {
    this.setState({ yrAnchorEl: event.target })
    this.setState({ yrOpen: true });
}

handleSaClick = (event) => {
    this.setState({ saAnchorEl: event.target })
    this.setState({ saOpen: true });
}

以下是我尝试点击项目时的屏幕截图。如您所见,多年的下拉列表按预期工作,但另一个正在捕获“0”

以下是完整组件及其订阅的服务:

首先是组件:

    import React from "react";
    import { FormGroup, FormControl, Button, Menu, MenuItem } from '@material-ui/core';
    import MUIDataTable from "mui-datatables";
    import { MuiThemeProvider } from '@material-ui/core/styles';
    import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
    import { setBaseUrl } from '../services/part-id-upper-sa-service'
    import theme from '../theme';

    export default class ParIdUpperSaComponent extends React.Component {
        state = {
            data: [],
            Header: [],
            totalCount: 10,
            options: {
                pageSize: 16,
                page: 0,
                filterType: "dropdown",
                selectableRows: false,
                responsive: "scroll",
                resizableColumns: true,
                className: this.name,
                textLabels: {
                    body: {
                        noMatch: this.props.isLoading ?
                            '' :
                            'Please wait while processing...',
                    },
                },
            },
            divAnchorEl: null,
            yrValue: '2020',
            yrOpen: false,
            yrAnchorEl: null,
            yrs: [],
            saValue: 'sa',
            saOpen: false,
            saAnchorEl: null,
            sa: ["sa","notSa"],
            isLoading: true,
            isPartIdUpperSa: true
        }

        componentDidMount() {
            // create array of years for the past 18 years
            const currentYr = new Date().getFullYear();
            for(let x = 0; x < 18; x++) {
                this.state.yrs.push(currentYr - x );
            }

            this.subscription = getPartIdUpperSa().subscribe((res) => {
                this.setState({ data: res });

                this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
                this.setState({ isLoading: false });
                this.setState({ Header: [
                    {
                        label: "Part ID",
                        name: 'part_id_upper',
                        options: {
                            className: 'first-col'
                        }
                    },
                    {
                        label: "Seq",
                        name: 'sequence',
                        options: {
                            className: 'sec-col'
                        }
                    },
                    {
                        label: "Qty",
                        name: 'quantity',
                        options: {
                            className: 'sm-col'
                        }
                    },
                    {
                        label: "Dt Orig",
                        name: 'date_originated',
                        options: {
                            className: 'mid-col'
                        }
                    },
                    {
                        label: "Div",
                        name: 'code_division',
                        options: {
                            className: 'sm-col'
                        }
                    },
                ]});
                this.setState({
                    totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
                });
            })
        }

        componentWillUnmount() {
            // unsubscribe to ensure no memory leaks
            this.subscription.unsubscribe();
        }

        handleYrChange = (event) => {
            console.log('handleYrChange: ' + event.target.value);
            // this.setState({value: event.target.value ? event.target.value : ''});
            this.setState({ data: [] });
            getPartIdUpperSa(event.target.value).subscribe((res) => {
                this.setState({ data: res });
                this.setState({ isLoading: false });
            });
            this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
            this.setState({ yrValue: event.target.value });
            this.onCloseYr();
        }

        handleSaChange = (event) => {
            console.log('handleSaChange: ' + event.target.value);

            if(event.target.value === 'notSa') {
                this.setState({ isPartIdUpperSa: false });
            } else {
                this.setState({ isPartIdUpperSa: true });        
            }

            setBaseUrl(event.target.value);
            this.setState({ saValue: event.target.value });
            this.onCloseSa();
        }

        handleYrClick = (event) => {
            this.setState({ yrAnchorEl: event.target })
            this.setState({ yrOpen: true });
        }

        handleSaClick = (event) => {
            this.setState({ saAnchorEl: event.target })
            this.setState({ saOpen: true });
        }

        onCloseYr = () => {
            this.setState({ yrOpen: false });
        }

        onCloseSa = () => {
            this.setState({ saOpen: false });
        }

        render() {
            let arrayofSa = this.state.sa;
            let saDropDown = arrayofSa.map((sa) => 
                <MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
                    {sa}
                </MenuItem>              
            );
            let arrayOfYrs = this.state.yrs;
            let yrDropDown = arrayOfYrs.map((yrs) =>
                <MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
                    {yrs}
                </MenuItem>           
            );
            return (
                <div>
                <MuiThemeProvider theme={theme}>
                    <FormGroup column='true'>
                        <FormControl>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
                                Select Sa or NotToSa
                            </Button>
                            <Menu id="sa-menu" open={this.state.saOpen}
                                anchorEl={this.state.saAnchorEl}  onClose={this.onCloseSa}
                                defaultValue={this.state.saValue ? this.state.saValue : ''} >
                                    {saDropDown}
                            </Menu>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
                                Select Year
                            </Button>
                            <Menu id="yrs-menu" open={this.state.yrOpen}
                                anchorEl={this.state.yrAnchorEl}  onClose={this.onCloseYr}
                                defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
                                    {yrDropDown}
                            </Menu>
                        </FormControl>
                    </FormGroup>
                </MuiThemeProvider>

                    {this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
                    <MUIDataTable
                    title="Part ID Upper Sa / Not Sa Report"
                    data={ this.state.data }
                    columns={ this.state.Header }
                    options={ this.state.options }
                    />
                </div>
            );
        }
        }

服务内容如下:

    import { ajax } from "rxjs/ajax";
    import { Observable } from "rxjs";

    let base_url = 'https://localhost:5001/PartIdUpperSa';

    export const getBaseUrl = () => {
        return base_url;
    }

    export const setBaseUrl = (param) => {
        console.log("from within setBaseUrl: " + param);
        if(param === 'notSa') {
            base_url = 'https://localhost:5001/PartIdUpperNotSa';
        } else {
            base_url = 'https://localhost:5001/PartIdUpperSa';
        }
    }

    let state = {
        data: []
    }

    export const getPartIdUpperSa = (yr) => {
        return new Observable(observe => {
            let mYr = new Date().getFullYear();
            let tempYr = (yr)? yr : mYr;
            state.data = ajax
            .get(base_url + "/" + tempYr)
            .subscribe(resu => {
                state.data = resu.response ;
                // console.log("from within getPartIdUpperSa: " + JSON.stringify(resu.response));
                observe.next(resu.response);
            });
        });
    }

像往常一样,提前致谢

我找到了解决方法。如果有人能解释为什么这样做,那么我将不胜感激。

该组件现在使用数字而不是名为 "sa," 的数组中的字符,这使其按预期运行。

我用过这个:

sa: ["1","2"],

而不是这个:

sa: ["sa","notSa"],

成功了,下面是完整的组件:

    import React from "react";
    import { FormGroup, FormControl, Button, Menu, MenuItem } from '@material-ui/core';
    import MUIDataTable from "mui-datatables";
    import { MuiThemeProvider } from '@material-ui/core/styles';
    import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
    import { setBaseUrl } from '../services/part-id-upper-sa-service'
    import theme from '../theme';

    export default class ParIdUpperSaComponent extends React.Component {
        state = {
            data: [],
            Header: [],
            totalCount: 10,
            options: {
                pageSize: 16,
                page: 0,
                filterType: "dropdown",
                selectableRows: false,
                responsive: "scroll",
                resizableColumns: true,
                className: this.name,
                textLabels: {
                    body: {
                        noMatch: this.props.isLoading ?
                            '' :
                            'Please wait while processing...',
                    },
                },
            },
            divAnchorEl: null,
            yrValue: '2020',
            yrOpen: false,
            yrAnchorEl: null,
            yrs: [],
            saValue: '1',
            saOpen: false,
            saAnchorEl: null,
            sa: ["1","2"],
            isLoading: true,
            isPartIdUpperSa: true
        }

        componentDidMount() {
            // create array of years for the past 18 years
            const currentYr = new Date().getFullYear();
            for(let x = 0; x < 18; x++) {
                this.state.yrs.push(currentYr - x );
            }

            this.subscription = getPartIdUpperSa().subscribe((res) => {
                this.setState({ data: res });

                this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
                this.setState({ isLoading: false });
                this.setState({ Header: [
                    {
                        label: "Part ID",
                        name: 'part_id_upper',
                        options: {
                            className: 'first-col'
                        }
                    },
                    {
                        label: "Seq",
                        name: 'sequence',
                        options: {
                            className: 'sec-col'
                        }
                    },
                    {
                        label: "Qty",
                        name: 'quantity',
                        options: {
                            className: 'sm-col'
                        }
                    },
                    {
                        label: "Dt Orig",
                        name: 'date_originated',
                        options: {
                            className: 'mid-col'
                        }
                    },
                    {
                        label: "Div",
                        name: 'code_division',
                        options: {
                            className: 'sm-col'
                        }
                    },
                ]});
                this.setState({
                    totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
                });
            })
        }

        componentWillUnmount() {
            // unsubscribe to ensure no memory leaks
            this.subscription.unsubscribe();
        }

        handleYrChange = (event) => {
            console.log('handleYrChange: ' + event.target.value);
            this.setState({ data: [] });
            getPartIdUpperSa(event.target.value).subscribe((res) => {
                this.setState({ data: res });
                this.setState({ isLoading: false });
            });
            this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
            this.setState({ yrValue: event.target.value });
            this.onCloseYr();
        }

        handleSaChange = (event) => {
            console.log('handleSaChange: ' + event.target.value);

            if(event.target.value === '2') {
                this.setState({ isPartIdUpperSa: false });
            } else {
                this.setState({ isPartIdUpperSa: true });        
            }

            setBaseUrl(event.target.value);
            this.setState({ saValue: event.target.value });
            this.onCloseSa();
        }

        handleYrClick = (event) => {
            this.setState({ yrAnchorEl: event.target })
            this.setState({ yrOpen: true });
        }

        handleSaClick = (event) => {
            this.setState({ saAnchorEl: event.target })
            this.setState({ saOpen: true });
        }

        onCloseYr = () => {
            this.setState({ yrOpen: false });
        }

        onCloseSa = () => {
            this.setState({ saOpen: false });
        }

        render() {
            let arrayofSa = this.state.sa;
            let saDropDown = arrayofSa.map((sa) => 
                <MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
                    {sa}
                </MenuItem>              
            );
            let arrayOfYrs = this.state.yrs;
            let yrDropDown = arrayOfYrs.map((yrs) =>
                <MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
                    {yrs}
                </MenuItem>           
            );
            return (
                <div>
                <MuiThemeProvider theme={theme}>
                    <FormGroup column='true'>
                        <FormControl>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
                                Select Sa or NotToSa
                            </Button>
                            <Menu id="sa-menu" open={this.state.saOpen}
                                anchorEl={this.state.saAnchorEl}  onClose={this.onCloseSa}
                                defaultValue={this.state.saValue ? this.state.saValue : ''} >
                                    {saDropDown}
                            </Menu>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
                                Select Year
                            </Button>
                            <Menu id="yrs-menu" open={this.state.yrOpen}
                                anchorEl={this.state.yrAnchorEl}  onClose={this.onCloseYr}
                                defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
                                    {yrDropDown}
                            </Menu>
                        </FormControl>
                    </FormGroup>
                </MuiThemeProvider>

                    {this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
                    <MUIDataTable
                    title="Part ID Upper Sa / Not Sa Report"
                    data={ this.state.data }
                    columns={ this.state.Header }
                    options={ this.state.options }
                    />
                </div>
            );
        }
    }

以下是组件订阅的服务:

    import { ajax } from "rxjs/ajax";
    import { Observable } from "rxjs";

    let base_url = 'https://localhost:5001/PartIdUpperSa';

    export const getBaseUrl = () => {
        return base_url;
    }

    export const setBaseUrl = (param) => {
        console.log("from within setBaseUrl: " + param);
        if(param == '1') {
            base_url = 'https://localhost:5001/PartIdUpperSa';
        } else {
            base_url = 'https://localhost:5001/PartIdUpperNotSa';
        }
    }

    let state = {
        data: []
    }

    export const getPartIdUpperSa = (yr) => {
        return new Observable(observe => {
            let mYr = new Date().getFullYear();
            let tempYr = (yr)? yr : mYr;
            state.data = ajax
            .get(base_url + "/" + tempYr)
            .subscribe(resu => {
                state.data = resu.response ;
                observe.next(resu.response);
            });
        });
    }

再一次,如果有人能解释为什么数字适用于 event.target.value 而字符不适用于,那么我将不胜感激。