//用useRef 来保存变量
import React,{useRef} from 'react'
function App8(){
const username =useRef(null);
const changeWord= ()=>{
username.current.value="Hello,好好学习React"
console.log(username)
}
return(
<>
<input type='text' ref={username} />
<button onClick={changeWord}>展示文字</button>
</>
)
}
export default App8;
效果图
现在我们尝试来改变值
//用useRef 来保存变量
import React,{useRef,useState,useEffect} from 'react'
function App8(){
const username =useRef(null);
const changeWord= ()=>{
username.current.value="Hello,好好学习React"
console.log(username)
}
//这里定义初始值
const [text,setText]= useState("我是初始值123")
const textRef = useRef();
useEffect(()=>{
textRef.current = text;
console.log('textRef.current'+textRef.current)
})
return(
<>
<input type='text' ref={username} />
<button onClick={changeWord}>展示文字</button>
<br/><br/>
<input value={text} onChange={(e)=>setText(e.target.value)} />
</>
)
}
export default App8;