Skip to content

Can I change switch value programmatically? #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
cnakh opened this issue Jan 20, 2018 · 4 comments
Open

Can I change switch value programmatically? #19

cnakh opened this issue Jan 20, 2018 · 4 comments

Comments

@cnakh
Copy link

cnakh commented Jan 20, 2018

Your component is very nice.

I have two toggle switch, if one on, the other one is off.
So when I click on the toggle switch it trigger the other to change it state.

How can I make the switch change value and animate by programmatically?

@poberwong
Copy link
Owner

emmming, I will do it recently and please give me some time.

@poberwong
Copy link
Owner

poberwong commented Mar 13, 2018

It's unnecessary to add animation when changing value programmatically. If u have to do it, the following code should be done:

  componentWillReceiveProps (nextProps) {
    if (nextProps === this.props) {
      return
    }

    // componentWillReceiveProps will still be triggered if
    // render function of father component is triggered.
    // Thus, toggleSwitch will be executed without two-way bind.
    if (typeof nextProps.value !== 'undefined' && nextProps.value !== this.props.value) {
      this.animateHandler(this.handlerSize * SCALE, () => {
        this.toggleSwitch(true)
      })
    }
  }

The SCALE is a variable valued 6 / 5.
If you want to prolong time of handler which is circle, you can use setTimeout in callback of animatedHandler,like following:

this.animateHandler(this.handlerSize * SCALE, () => {
  setTimeout(() => {
    this.toggleSwitch(true)
  }, yourTime)
})

@diaojinggang
Copy link
Contributor

diaojinggang commented Mar 23, 2018

I think I already did what @cnakh wanted in Nov, 2017. switch1 shows myState1, switch2 shows myState2. When switch1 is toggled, this.setState({myState1:val}); if(val == true) {this.setState({myState2:false})}. Apply the same logic to switch2. Isn't the idea just like this?

@ayberkanilatsiz
Copy link

ayberkanilatsiz commented Nov 14, 2018

@cnakh yes you can.

you need to ref the comp. Ex:

<Switch ref={ (comp) => this['switch'] = comp } value={value} onSyncPress={onValueChange} />

changeValue = (value) => { this.switch.toggleSwitchToValue(true,value); }

when you call the changeValue function, your switch will change.

@diaojinggang when you update state all page will be rendered again. It can not be necessary but if you have many switch your state will be too crowded. I think the best way is the ref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants