1.基本使用
import React, {useRef} from 'react'const UseRefFunc=()=>{const inputRef=useRef(null)const handle=()=>{console.log(inputRef.current.value);}return (<div><input type="text" ref={inputRef}/><button onClick={handle}>提交</button></div>)}export default UseRefFunc
useRef可以保存变量,dom以及事件 useRef(和React.creatRef()生成的有点类似)
useRef 返回一个可变的ref对象——-书写更加简洁
返回的ref对象在组件的整个生命周期内保持不变
ref对象的.current属性设置为相应的DOM节点————-和之前的ref一样的
当ref对象内容发生变化时,useRef并不会通知你————dom对象发生变化后,并不会实时更新ref
变更.current属性不会引发组件重新渲染————修改current属性,dom不会更新任何
2.保存数据
保存上一次的值
import React,{useRef,useState,useEffect,Fragment }from 'react'// orimport { Button } from 'react-bootstrap';import './App.css';function App() {const [count, setcount] = useState(0)const ref = useRef(count)//保存上一次的值useEffect(() => {ref.current=count}, [count])return (<div className="App">{<Fragment><h1>上一次的值:{ref.current}</h1><h1>这一次的值:{count}</h1><Button onClick={e=>setcount(count+10)} variant="primary">加10</Button></Fragment>}</div>);}export default App;
3.使用react-bootstreap
安装 yarn add react-bootstrap bootstrap
使用
//在index.html文件中引入css文件<!-- Latest compiled and minified CSS --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"><!-- Optional theme --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">
在组件中import { Button } from 'react-bootstrap';
