React+webpack+typescript(实现自动匹配搜索框)

301 阅读2分钟

React-demo1

使用webpack构建一个react项目。效果如下: AutoComplete.gif 参考地址:

www.jb51.net/article/247… blog.csdn.net/mChales_Liu…

TypeScript+Webpack+React

上述只是使用webpack构建了简单的react应用,使用的js语法,接下来探索如何用ts编写代码实现对应功能。参考地址:zhuanlan.zhihu.com/p/455297005

  • 首先安装与ts相关的插件
npm install awesome-typescript-loader source-map-loader
npm install ts-loader -D 
npm install typescript -D 
npx tsc --init  

上述生成tsconfig.json文件的命令使用npx tsc --init,而不是tsc --init因为,安装的typescript不是全局安装。参考blog.csdn.net/qq_41499782…

在次tsconfig.json文件中:

image.png

解决:修改webpack.common.js中的入口文件,

image.png

  • 配置babel支持typescript,在webpack.common.js修改babel配置,options增加@babel/preset-typescript

image.png

  • 修改tsconfig.jsonjsx项:
    "jsx": "react", 
  • npm run dev之后报错:

image.png

!!!!!忘记安装这个包了,npm install --save-dev @babel/preset-typescript

reactreact-dom这两个包代码中都不存在对应的类型声明,需要单独安装他们对应的类型声明文件: @types/react-dom @types/react

实现自动匹配搜索框

1. 需求分析

AutoComplete.gif

参考百度的搜索框,输入关键字,展示含有关键字的匹配下拉列表。

  • 输入框组件、下拉列表组件;
  • 输入字符串,进行匹配展示含有该字符串相关的数据;
  • 搜索匹配功能流程图: image.png

2.在搜索匹配的时候遇到的问题:

handleSearch(searchVal: string) {
        console.log('AutoComponent----', searchVal);
        console.log('AutoComponent----', data);
        //使用过滤器过滤
        this.setState({
            searchRe: ['dd', '33']
        })
        console.log('过滤', data.filter((item) => item.indexOf(searchVal) !== -1))
        console.log('searchRe----', this.state.searchRe)
        if (this.state.searchRe.length !== 0) {
            //匹配到搜索结果
            console.log('AutoComponent----', this.state.searchRe)//结果如下图所示:
        }
    }

this.state.searchRe结果: image.png 查阅官方文档:state的更新可能是异步的。

image.png

使用到属性dangerouslySetInnerHTML={{__html: item}}

matchRes.map((item: string) => {
            const newItem = item.replace(searchVal, `<span style='color: #9f95f7;'>${searchVal}</span>`);
            newRes.push(newItem);
        });
<ul className="match-ul">
                    {
                        newRes.map((item: string, index: number) => 
                            <li dangerouslySetInnerHTML={{__html: item}} className="item-li" key={index.toString()}>
                            </li>
                        )
                    }
</ul>

3. 结果

AutoComplete.gif