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')
    );
  • 相关阅读:
    此心本净四——圣言录·下·平等无分别
    此心本净三——圣言录·中·空性
    一饮一啄,自成因果
    心为何而动······
    此心漂泊
    喜欢看心的幻化
    (js描述的)数据结构[集合结构](6)
    (js描述的)数据结构[双向链表](5)
    (js描述的)数据结构[链表](4)
    微信小程序(黑马优购)完成!!{10天}
  • 原文地址:https://www.cnblogs.com/sx00xs/p/11785235.html
Copyright © 2011-2022 走看看