react经验10:与jquery配合使用

应用场景

老web项目进行react改造,为了节省时间,部分jquery组件仍然保留。

案例1

使用bootstrapTable组件。

node_modules准备

jquery、bootstrap、bootstrap-table

如果需要typescript,则额外追加

@types/bootstrap、@types/jquery

以上都直接npm安装。

实施步骤:

1.在src的index中挂载jquery到全局变量

import $ from 'jquery'
window.jQuery = $

2.在需要使用bootstrap-table的组件中引入插件

import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap-table/dist/bootstrap-table.min.css'
import $ from 'jquery'
import 'bootstrap'
import 'bootstrap-table'

接下来就能在合适的时机调用插件

//例如组件初始化的时候
useEffect(()=>{
	$(dom).bootstrapTable(option)
},[])

案例2

jquery与react混用,比如某段html是由jquery动态生成的,此时又想插入一段react组件。

实施步骤:
1.准备好普通的react组件;

const DemoComponent=(props:{})=>{
	return (
		<label>啊手动阀示范点</label>
	)
}

2.混合使用

//这是由jquery生成的dom
$('
').appendTo('body') //准备react组件的容器 let root=ReactDOM.createRoot(document.getElementById('demo') as HTMLElement) //渲染react组件 root.render(<DemoComponent />)

你可能感兴趣的:(web前端,react.js,jquery,前端,react)