React MenuItem event.target.value在一个菜单项中不起作用,但在另一个MenuItem中起作用

问题描述 投票:0回答:1

我有两个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”

screen shot of console log results

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

首先是组件:

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

和往常一样,提前致谢

reactjs menuitem
1个回答
0
投票

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

该组件现在使用数字而不是称为“ 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一起使用而字符不能使用,那么我将不胜感激。

和往常一样,提前致谢

© www.soinside.com 2019 - 2024. All rights reserved.