简体   繁体   中英

onChange Event Pooling for Slider component in Material UI

I am trying to handle onChange for a Material UI Slider by storing the value in a current array using useState . The slider is stuck if the prop Name is used but works in a weird slow way if i use the id prop. I think my issue is related to Event Pooling and the solution of using event.persist() at react docs explain the issue but i didnt know how to apply it to my code.

Here is my code:

import React, { useState, useEffect } from 'react';
import Slider from '@material-ui/core/Slider';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getSettings } from '../../actions/settingsActions';
   
const Settings = ({ getSettings, settings, loading }) => {


  React.useEffect(() => {
    getSettings();

    // eslint-disable-next-line
  }, []);

  const [current, setCurrent] = useState({
    ageAtDeath: 50,
    costInflation: 0,
   
  });

  React.useEffect(() => {
    if (!loading) {
      setCurrent({
        ageAtDeath: settings.ageAtDeath,
        costInflation: settings.costInflation,
        
      });
    }
    // eslint-disable-next-line
  }, [settings]);


  const {
    ageAtDeath,
    costInflation,
  } = current;

  const onChange = (event, newValue) => {
    setCurrent({
      ...current,
      [event.target.id]: newValue, //if i use event.target.name the slider is stuck
    });
  };

  
  return (   
              <Slider
                id='ageAtDeath'
                name='ageAtDeath'
                value={ageAtDeath}
                onChange={onChange}
                step={5}
                marks
                min={60}
                max={100}
                valueLabelDisplay='on'
              />
  
  );
};

Settings.propTypes = {
  getSettings: PropTypes.func.isRequired,
  settings: PropTypes.object,
  loading: PropTypes.bool.isRequired,
};

const mapStateToProps = (state) => ({
  settings: state.settings.settings,
  loading: state.settings.loading,
});

export default connect(mapStateToProps, {
  getSettings,
})(Settings);

I solved this by following the answer from this post .

Here is the final code.

const onChange = (name) => (e, value) => {
    setCurrent({
      ...current,
      [name]: value,
    });
  };

make sure to add the name of the value you are changing when calling onChange

                   <Slider
                    id='costInflation'
                    name='costInflation'
                    value={costInflation}
                    onChange={onChange('costInflation')}
                    min={0}
                    max={50}
                    valueLabelDisplay='on'
                  />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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