React.js 根据JSON形成级联选择器

时间:2019-06-18
本文章向大家介绍React.js 根据JSON形成级联选择器,主要包括React.js 根据JSON形成级联选择器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
export default class FinancialItemSelect extends React.Component {

    constructor(props, context){
        super(props, context);

        this.state={
            value: props.initialValue ? props.initialValue : "0-无"
        }
    }

    updateValue = (e) => {
        console.log(this.state.value);
        let val = e.target.value,
            path = e.target.dataset.path;
        this.props.update(`${path}-${val}`);
        this.setState({
            value: `${path}-${val}`
        })
    }

    renderSelect(pastPath, [curr, ...restPath], optionTree){

        // if reached the end (leaf) of the tree, return nothing.
        if(optionTree === undefined || Object.keys(optionTree).length === 0){
            return [];
        }

        // otherwise, list all options on this level
        let options = [];
        for(let key in optionTree){
            options.push(<option key={key} value={key}>{key}</option>);
        }

        // for the case there is possibly leaves, but not yet selected.
        let currPath = pastPath.concat(curr);
        if(restPath.length === 0){
            return [<div key={curr}><Select
                
                data-path={currPath.join('-')}
                onChange={(e) => this.updateValue(e)}
                onClick={(e)=> {
                    e.preventDefault();
                    e.stopPropagation();
                }}
            >{options}</Select></div>];
        } else {
            let [selected, ...rest] = restPath;
            return [<div key={curr}><Select
                
                data-path={currPath.join('-')}
                value={selected}
                onChange={(e) => this.updateValue(e)}
                onClick={(e)=> {
                    e.preventDefault();
                    e.stopPropagation();
                }}
            >{options}</Select></div>, ...this.renderSelect(currPath, restPath, optionTree[selected])]
        }
    }

    render(){
        return this.renderSelect([], this.state.value.split('-'), BalanceSheetCategory)
    }

}

  

原文地址:https://www.cnblogs.com/marvintau/p/11043698.html