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

2019/06/18 10:10
阅读数 62
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)
    }

}

  

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部