zoukankan      html  css  js  c++  java
  • React练习 1 :控制div属性

    在线效果浏览

    需求: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=[
        {'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')
    );
  • 相关阅读:
    mysql的启动出现错误 install/remove denied错误操作
    mybatis的开发方式
    mysql绿色版安装出现1067的错误原因
    线程池中对于异常的处理操作
    spring中的aync注解的使用与事务操作
    互联网金融产品经理 修炼之道
    几句牢骚
    做自己
    自动加载与访问权限
    mvc模式实现
  • 原文地址:https://www.cnblogs.com/sx00xs/p/11785235.html
Copyright © 2011-2022 走看看