需求:5個按鈕,點擊后分別修改 1 個div元素的一項屬性
2個組件:
父組件:App
a 利用 hook useRef 獲取 div元素的引用,並傳遞給子組件 Myinput
b 數據源數組 styles,使用數組函數 map 返回一個mybtns數組,由5個Myinput子組件組成
子組件:Myinput
綁定 onClick,根據傳入的 props.index來判斷需設置元素的何種屬性
import React,{useRef} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function Myinput(props){ const handleClick=function(){ const index=props.index; const item=props.item; const style=props.btns.current.style; switch(index){ case 0: style.width=item.width; break; case 1: style.height=item.height; break; case 2: style.background=item.background; break; case 3: style.display=item.display; break; case 4: style.display=item.display; style.width='100px'; style.height='100px'; style.background='black'; break; default:style.width=item.width; } }; return( <input type="button" value={props.value} onClick={handleClick}/> ); } function App(){ const btns=useRef(null); const styles=[ {width:'200px',value:'變寬'}, {height:'200px',value:'變高'}, {background:'red',value:'變色'}, {display:'none',value:'隱藏'}, {display:'block',value:'重置'} ]; const mybtns=styles.map(function(item,index){ return <Myinput btns={btns} item={item} index={index} value={item.value} key={item.value}/> }) return( <div className="outer"> {mybtns} <div ref={btns} className="div1"></div> </div> ); } ReactDOM.render( <App/>, document.getElementById('root') );