Get material ui slider value in onDragStop event (react)

笑着哭i 提交于 2020-06-25 10:26:10

问题


I want to fire an event onDragStop rather than onChange using a material ui Slider in my React app (so that the event fires fewer times). However, the documentation indicates that the onDragStop function signature only has the mouseevent: function(event: object) => void. So, the following works with onChange:

<Slider onChange={ (e, val) => this.props.update(e, control.id, val) } />

However, this event doesn't have a second parameter val:

<Slider onDragStop={ (e, val) => this.props.update(e, control.id, val) } />

How can I get the current value of the Slider in the onDragStop function? Note, I'm unable to use this, as it refers to the parent component.


回答1:


Also ran into this problem! If you use a component inside a class, use both callbacks:

<Slider onChange={ (e, val) => this.val = val }  
        onDragStop={ (e) => this.props.update(e, control.id, this.val)
/>



回答2:


In a newer version of Material UI you could use:

<Slider
  onChange={} // for example updating a state value
  onChangeCommitted={} // for example fetching new data
/>



回答3:


If you want the Slider value to be part of the component state, e.g. for triggering a re-render of the Slider when it changes (this requires you to pass this.state.value to the Slider as well), you can do this:

class Parent extends Component {
    render() {
        return <Slider value={this.state.value} onChange={this.handleChange} onDragStop={this.handleDragStop}/>
    }

    handleChange = (event, value) => this.setState({ value });

    handleDragStop = () => this.props.update(this.state.value);
}

Otherwise you can just assign the value to this:

class Parent extends Component {
    render() {
        return <Slider onChange={this.handleChange} onDragStop={this.handleDragStop}/>
    }

    handleChange = (event, value) => this.value = value;

    handleDragStop = () => this.props.update(this.value);
}


来源:https://stackoverflow.com/questions/47440051/get-material-ui-slider-value-in-ondragstop-event-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!