react搜索组件--传入数据,回调

/**
* @method 搜索组件
* 参数:本次搜索分为两种情况 1.传入数据进行
* isTreeData:true
* staus:false 禁用状态 父组件配合
* TreeData:[]
* isChir:”” 是否显示含有子节点的节点
* isChirStr:”” 区分是否含有子节点的字段 字符串 对应判断的值为true和falsa(方法内置)
* onSearchClick:function 点击搜索结果回调 参数为点击的数据对象
* onChange:function 搜索框的值改变时回调
* onSearchEnter:function 点击enter时回调 参数是搜索框里的数据
*/

import React, { Component } from 'react';

export class SearchTree extends Component {
constructor(props) {
    super(props);
    this.state = {
        //搜索框的值
        searchValue: "",
        //  搜索出来的数据是否显示
        serchDataIsshow: false,
        //  搜索出来的数据
        serchData: [],
    }
    // 被搜索树的ID
    this.TreeId = this.props.TreeId;
    // 是否需要显示出带子节点的树节点 默认不显示
    this.isChir = this.props.isChir || false;
    this.isChirStr = this.props.isChirStr || "";
    // localStorage.historyData = "";
}
onChange = (e) => {
    console.log(e);
    let eValue = e.target.value;
    this.setState({ searchValue: e.target.value }, () => {
        let data;
        let NewData = [];
        //打开搜索框
        this.setState({ serchDataIsshow: true });
        if (this.TreeId || this.props.isTreeData) {
            if (this.props.isTreeData) {
                data = this.props.TreeData;
            } else {
                data = this.props.syncTree.getSyncTreeValue(this.TreeId);
            }
            console.log("搜索出来的数据 !", isArray(data));
            console.log("搜索出来的数据 !", data);
            if (!isArray(data)) {
                alert("数据格式错误,请修改,或联系管理员 Mendege !");
                return;
            }

            NewData = this.onSearchDataFn({ data: data, str: eValue });
            this.setState({ serchData: NewData });
        }
        //数据变动回调
        if (this.props.onChange instanceof Function) {
            this.props.onChange(e);
        }
    });

}
//搜索事件
onSearch = (e) => {
    // console.log("搜索参数", e);
    let flagObject = this.onisEnter(this.state.serchData);
    if (flagObject.flag) {
        if (this.props.onSearchClick instanceof Function) {
            this.props.onSearchClick(flagObject.data);
            this.addHistoryData(flagObject.data);
            //关闭搜索框
            this.setState({ serchData: [], serchDataIsshow: false, searchValue: "" });
        }
    }

    // console.log(data);

}
//enter键 直接搜索 第一个
onisEnter = (data) => {
    let flagObject = { flag: false };
    for (let i = 0, length = data.length; i < length; i++){
        let items = data[i];
        // 模糊搜索第一个
        if (!items.isHisName) {
            flagObject.flag = true;
            flagObject.data = items;
            break;
        }
        // 该功能是保证搜索框里的值和预期值一样才开启搜索功能
        // if (items.refname === this.state.searchValue) {
        //     flagObject.flag = true;
        //     flagObject.data = items;
        // }
    }
    return flagObject;
}
//向历史记录中添加数据
addHistoryData = (data) => {
    let histName = { refname: "历史记录(名称)", isHisName: true }
    if (!localStorage.historyData) {
        localStorage.historyData = JSON.stringify([histName, data]);
    } else {
        let historyData = JSON.parse(localStorage.historyData);
        //是否启用热度机制
        let isHeat = false, isHeatNum;
        historyData.map((items, keys) => {
            if (items.refname == data.refname) {
                isHeat = true;
                isHeatNum = keys;
            }

        })
        // console.log(isHeat);
        if (!isHeat) {
            historyData.splice(1, 0, data);
        } else {
            historyData.splice(isHeatNum, 1);
            historyData.splice(1, 0, data);
            // let viData = historyData.splice(isHeatNum,1);
            // console.log("添加---",viData);
            // console.log("添加---==",historyData);

        }
        if (historyData.length > 6) {
            historyData.length = 6
        }

        localStorage.historyData = JSON.stringify(historyData);

    }
}
//根据传入的值搜索出目标数据中拥有的数据
onSearchDataFn = (dataObject) => {
    let data = dataObject.data;
    let str = dataObject.str;
    let newData = [];
    const newDataFn = (virtualData) => {
        virtualData.map((items, keys) => {
            if (dataObject.flag) {
                if (dataObject.flag == "search") {
                    if (items.refname == str) {
                        if (items[this.isChirStr] === true) {
                            newData.push(items);
                        }
                    }
                }
            } else {
                if (items.refname.search(str) != -1) {
                    if (items[this.isChirStr] === true) {
                        newData.push(items);
                    } else {
                        if (this.isChir) {
                            newData.push(items);
                        }
                    }

                }
            }
            if (items.children && isArray(items.children)) {
                if (items.children.length > 0) {
                    newDataFn(items.children);
                }
            }
        });

    }
    newDataFn(data)
    return newData;
    // data.map((items,keys)=>{

    // });




}
//键盘抬起事件
onKeyUp = (e) => {
    if (this.state.searchValue == "") {
        if (localStorage.historyData) {
            if (e.keyCode == 8) {
                let data = JSON.parse(localStorage.historyData)
                data = this.filtrateLocData(data);
                this.setState({ serchData: JSON.parse(localStorage.historyData), serchDataIsshow: true });
            }
        }
    }
}
//键盘按下事件
onKeyDown = (e) => {
    let flagObject = this.onisEnter(this.state.serchData);
    if (e.keyCode == 13) {
        if (flagObject.flag) {
            if (this.props.onSearchClick instanceof Function) {
                this.props.onSearchClick(flagObject.data);
                this.addHistoryData(flagObject.data);
                //关闭搜索框
                this.setState({ serchData: [], serchDataIsshow: false, searchValue: "" });
            }

        }
    }
    // console.log("修改====",flagObject)
    //enter回调
    if (this.props.onSearchEnter instanceof Function) {
        this.props.onSearchEnter(this.state.searchValue);
    }
}
//清除浏览记录
ClearRecord = () => {
    localStorage.historyData = '[{"refname":"历史记录(名称)","isHisName":true}]';
    this.setState({ serchData: [] });
}
//渲染搜索出来的数据
onSearchHtml = (dataObject) => {
    let data = dataObject.data;
    let NewHtml = [];
    let that = this;
    let i = 0;
    data.map((items, keys) => {
        if (items.refname) {
            if (items.isHisName) {
                NewHtml.push(
  • {items.refname} 清除记录
  • ); } else { NewHtml.push(
  • { that.onSearchClick(e); }} data-key={keys}>{items.refname}
  • ); } } }); return NewHtml; } //点击搜索出来的结果 onSearchClick = (e) => { //获取数据索引 let dataKey = e.target.getAttribute("data-key"); //点击得到的数据索引 let data = this.state.serchData[dataKey]; //关闭搜索框 this.setState({ serchData: [], serchDataIsshow: false, searchValue: "" }); this.addHistoryData(data); //点击回调 if (this.props.onSearchClick instanceof Function) { this.props.onSearchClick(data); } } //获取焦点事件 onFocus = (e) => { let eValue = e.target.value; if (eValue == "") { if (this.state.searchValue == "") { if (localStorage.historyData) { // localStorage.historyData = "" let data = JSON.parse(localStorage.historyData) data = this.filtrateLocData(data); this.setState({ serchData: data, serchDataIsshow: true }); } } } else { let data; let NewData = []; //打开搜索框 this.setState({ serchDataIsshow: true }); if (this.TreeId || this.props.isTreeData) { if (this.props.isTreeData) { data = this.props.TreeData; } else { data = this.props.syncTree.getSyncTreeValue(this.TreeId); } if (!isArray(data)) { alert("数据格式错误,请修改,或联系管理员 Mendege !"); return; } NewData = this.onSearchDataFn({ data: data, str: eValue }); this.setState({ serchData: NewData }); } } } //失去焦点事件 onBlur = (e) => { let that = this; // console.log(e.target.className) // if(){ // } // that.setState({ serchData: [], serchDataIsshow: false, searchValue: "" }); //关闭搜索框 // setTimeout(()=>{ // },0); } //首次加载 componentDidMount() { //绑定消失的事件 document.addEventListener('click', this.handleClick); } //组件销毁时解绑事件 componentWillMount() { document.removeEventListener('click', this.handleClick); } //点击外部隐藏 handleClick = (e) => { const contains = (root, n) => { var node = n; while (node) { if (node === root) { return true; } node = node.parentNode; } return false; } if (!contains(this.refRoot, e.target)) { this.setState({ serchDataIsshow: false }); } } //筛选历史记录是不是在当前数据中存在 filtrateLocData = (lData) => { let num = []; lData.map((items, keys) => { let data; let NewData = []; //打开搜索框 if (this.TreeId || this.props.isTreeData) { if (this.props.isTreeData) { data = this.props.TreeData; } else { data = this.props.syncTree.getSyncTreeValue(this.TreeId); } if (!isArray(data)) { alert("数据格式错误,请修改,或联系管理员 Mendege !"); return; } NewData = this.onSearchDataFn({ data: data, str: items.refname, flag: "search" }); if (NewData.length === 0 && !items.isHisName) { num.unshift(keys); } } }); if (num.length > 0) { num.map((items, keys) => { lData.splice(items, 1); }); } localStorage.historyData = JSON.stringify(lData); return lData; } render() { let status = this.props.status; return (
    { this.refRoot = ref }} style={{ position: "relative", maxWidth: 250, minWidth: 180 }}>
    { status ? : }
    { this.state.serchDataIsshow ?
      { this.onSearchHtml({ data: this.state.serchData }) }
    : null }
    ) }

    }

    你可能感兴趣的:(组件)