简体   繁体   English

如何在 React.js 上运行多个函数?

[英]How to run multiple functions at React.js?

Currently, I'm making a system that can control home electrical equipment on the web.目前,我正在制作一个可以在 web 上控制家用电器设备的系统。 Backend is ready, I'm trying to implement a function to adjust the brightness of the light with a slider.后端已准备就绪,我正在尝试实现 function 以使用 slider 调整灯光的亮度。

在此处输入图像描述

I can set brightness_value variable is assigned a number from 0 to 100 when the slider is moved with the code below.当使用下面的代码移动 slider 时,我可以设置亮度值变量被分配一个从 0 到 100 的数字。

<input type="range" name="speed" min="0" max="100" 
                value={brightness_value} onChange={(e) => setBrightnessValue(e.target.value)}></input>

The problem is that I want to fire the lightOn function at the same time as I move the slider but I don't know what to do.问题是我想在移动 slider 的同时点亮 lightOn function 但我不知道该怎么做。 (I'm already using onChange, so can't I use it?) (我已经在用onChange了,不能用吗?)

LightDetail.js LightDetail.js

import React, { useState, useEffect, useCallback, onClick} from 'react';
import axios from 'axios';
import ic_light from "../../images/icons/ic_light.png"

const LightDetail = () => {

  const [light, setLight] = useState([]);

  const [brightness_value, setBrightnessValue] = useState();


// set light strength
  const lightOn = async(data) => {
    await axios.post('xxx.com/light/turn_on',
      {
        brightness: brightness_value
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Turn on!');
        getDevices();
      })
      .catch(err => {
        console.log('Turn on Missed!');
      });
  }

// get light data from backend
const getDevices = async(data) => {
  await axios.get('xxx.com/device_listr',
    {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${cookies.get('accesstoken')}`
      },
    })
    .then(result => {
      console.log(result.data)
      setLight(result.data.attributes.light);  
    })
    .catch(err => {
      console.log(err);
    });
}

useEffect(() => {
  getDevices();
    }, []);


  return (
    <div className="container">
      <div className="row mx-auto text-center">
          <>
            {light.map((item,i) => 
              <div key={i} className="col-12">
                <div className="box h-100">
                <img className="" src={ic_light} />
                <input type="range" name="speed" min="0" max="100" 
                value={brightness_value} onChange={(e) => setBrightnessValue(e.target.value)}></input><br></br>
                <Link to={`/device_list`} className='btn btn-primary col-4'>Back</Link>
                </div>
              </div>
            )}

          </>
      </div>
    </div>
  );
}
export default LightDetail;

You can define onChange as a custom event handler where you can do whatever.您可以将 onChange 定义为自定义事件处理程序,您可以在其中执行任何操作。

Example snippet:示例片段:

const handleSliderChange = (e) => {
  setLightOn(e.target.value)
  setBrightnessValue(e.target.value)
}

...

<input type="range" name="speed" min="0" max="100" 
                value={brightness_value} onChange={handleSliderChange} />

You should use the state to drive the view of the view to do你应该使用state来驱动视图的视图来做

Just add只需添加

useEffect(() => {
  lightOn()
}, [brightness_value])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM