简体   繁体   English

为 setState 反应钩子

[英]React Hooks for setState

I am trying to figure out how to use Hooks to display the number that a slider is at.我想弄清楚如何使用 Hooks 来显示滑块所在的数字。 This number should change as the slider moves.这个数字应该随着滑块的移动而改变。 I had this working without hooks, but now I'm trying to make it work with them as I think it's important to learn.我在没有钩子的情况下工作,但现在我正试图让它与他们一起工作,因为我认为学习很重要。 I feel like I'm close to solving this, but there's just some knowledge that I don't have that I need to make it work.我觉得我快要解决这个问题了,但是我没有一些知识,我需要让它发挥作用。 Have any advice or help?有什么建议或帮助吗? Thanks!谢谢! I left my previous code attached commented out so you can see how it worked.我把我以前的代码注释掉了,这样你就可以看到它是如何工作的。 My code below:我的代码如下:

JS(Babel): JS(巴别塔):

Slider = () => {
// function Slider() {

  const [value, setValue] = useState(120.5);
  // state = { value: 120.5 };

  useEffect(() => {})
  // onUpdate(e) {
  //   this.setState({
  //     value: e.target.value
  //   });
  // }  

  return (
    <div className="slider-box">
      <div>
        <label className="slider-label">{value}c</label>
        <p className="slider-title">Scale</p>
      </div>
      <StyledSlider
        list="tickmarks"
        max={1200}
        onChange={() => setValue(value + 1)}
        step={0.01}
        type="range"
        value={value} //{this.state.value}
      />
      <div> 
        <p className="slider-scale">1200 x 1200</p>
      </div>
    </div>
  );
}

You can do that using the same logic you were before.您可以使用与以前相同的逻辑来做到这一点。 There is no reason to increment your state one by one, just use the value you get from the event like you were doing previously in your onUpdate handler.没有理由一一增加您的状态,只需使用您从事件中获得的值,就像您之前在onUpdate处理程序中所做的那样。

Slider = () => {
// function Slider() {

  const [value, setValue] = useState(120.5);
  // state = { value: 120.5 };


  const onUpdate = (e) => {
     setValue(e.target.value);

   }  

  return (
    <div className="slider-box">
      <div>
        <label className="slider-label">{value}c</label>
        <p className="slider-title">Scale</p>
      </div>
      <StyledSlider
        list="tickmarks"
        max={1200}
        onChange={onUpdate}
        step={0.01}
        type="range"
        value={value} //{this.state.value}
      />
      <div> 
        <p className="slider-scale">1200 x 1200</p>
      </div>
    </div>
  );
}

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

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