在react中要做雙向綁定,必須使用react API "noChange",不然資料會被綁死不能使用。
import React, { useState } from 'react'
import './app3.scss';
export default function App3() {
const [goname, goName] = useState({M_Name:'',S_Name:''});
return (
<div className="div_bg">
<div className="main_bg">
1.<input type="text" value={goname.M_Name} onChange={(e)=>goName({M_Name:e.target.value})}/>
2.<input type="text" value={goname.S_Name} onChange={(e)=>goName({S_Name:e.target.value})}/>
<div><h1>輸入值1:{goname.M_Name}</h1><h1>輸入值2:{goname.S_Name}</h1></div>
</div>
</div>
)
}
範例:https://codesandbox.io/s/beautiful-bell-079os
這樣寫雖然可以輸入,H1也可以顯示輸入的值,可是有一個很大的問題,每當輸入一個輸入值,另一個就會被清空,這樣不行,於是找了找解決方法找到下面這個方式。
import React, { useState } from 'react'
import './app3.scss';
export default function App3() {
const [goname, goName] = useState({M_Name:'',S_Name:''});
return (
<div className="div_bg">
<div className="main_bg">
1.<input type="text" value={goname.M_Name} onChange={(e)=>goName({...goname,M_Name:e.target.value})}/>
2.<input type="text" value={goname.S_Name} onChange={(e)=>goName({...goname,S_Name:e.target.value})}/>
<div><h1>輸入值1:{goname.M_Name}</h1><h1>輸入值2:{goname.S_Name}</h1></div>
</div>
</div>
)
}
範例:https://codesandbox.io/s/busy-star-blh2d