【问题标题】:How to change style of element using ref in react js如何在 React js 中使用 ref 更改元素的样式
【发布时间】:2021-10-03 14:24:19
【问题描述】:

所以我正在尝试创建一个排序算法可视化器,我遇到了一个问题,我想用新的随机高度更新循环到列表中的每个 div。

import React, { useState, useRef } from 'react'
import "../styling/Sorting.css";
import Slider from '@material-ui/core/Slider';

function Sorting() {
    const [value, setValue] = useState(0);
    
    const changeValue = (event, newValue) => {
        setValue(newValue)
    }

    const barRef = useRef()

    function randomHeight(){
        var number1 = Math.floor(Math.random(10) * 500);

        barRef.current.style.height = number1 + "px";
    }

    return (
        <div className="container">
            <nav>
                <div className="slider">
                    <Slider value={value} onChange={changeValue} max={30} valueLabelDisplay="on"/>
                </div>
                <div className="random_height">
                    <button onClick={randomHeight}>random</button>
                </div>
            </nav>
            <div className="bars">
                {Array.from({ length: value }, (_, i) => <div className="bar" id="bar" ref={barRef} key={i}></div>
                    )}
            </div>
        </div>
    )
}

export default Sorting

但是我只能更改当前 div,它是添加到数组中的最后一个 div。

【问题讨论】:

    标签: javascript reactjs use-ref


    【解决方案1】:

    你需要管理多个 refs,例如:

    import React, { useState, useRef } from "react";
    import "../styling/Sorting.css";
    import Slider from "@material-ui/core/Slider";
    
    function Sorting() {
      const [value, setValue] = useState(0);
    
      const changeValue = (event, newValue) => {
        setValue(newValue);
      };
    
      const barRef = useRef([]);
    
      function randomHeight() {
        barRef.current.forEeach((node) => {
          const number1 = Math.floor(Math.random(10) * 500);
          node.style.height = number1 + "px";
        });
      }
    
      return (
        <div className="container">
          <nav>
            <div className="slider">
              <Slider
                value={value}
                onChange={changeValue}
                max={30}
                valueLabelDisplay="on"
              />
            </div>
            <div className="random_height">
              <button onClick={randomHeight}>random</button>
            </div>
          </nav>
          <div className="bars">
            {Array.from({ length: value }, (_, i) => (
              <div
                className="bar"
                id="bar"
                ref={(node) => (ref.current[i] = node)}
                key={i}
              ></div>
            ))}
          </div>
        </div>
      );
    }
    
    export default Sorting;
    

    【讨论】:

    • 感谢您的回答,我找到了一种不使用 refs 的不同方式!
    猜你喜欢
    • 2016-02-09
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多