标签:使用 button ons user ret 元素 http spl 获取
需求: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‘)
);
标签:使用 button ons user ret 元素 http spl 获取
原文地址:https://www.cnblogs.com/sx00xs/p/11785235.html