• 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')
    );
  • 相关阅读:
    html5新增元素和废除元素
    html5本地存储
    第四章表单与文件笔记新增属性
    第五章canvas
    lable中for的作用
    第四章表单与文件学习内容
    第三章html5的结构
    html5的全局属性
    正则表达式—升华
    微前端
  • 原文地址:https://www.cnblogs.com/sx00xs/p/11785235.html
Copyright © 2020-2023  润新知