How to set default Checked in checkbox ReactJS?

前端 未结 16 1978
难免孤独
难免孤独 2020-11-27 11:51

I\'m having trouble to update the checkbox state after it\'s assigned with default value checked="checked" in React.

var rCheck = React         


        
16条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 12:26

    I set the state as any[] type. and in the constructor set the state to null.

    onServiceChange = (e) => {
        const {value} = e.target;
        const index = this.state.services.indexOf(value);
        const services = this.state.services.filter(item => item !== value);
        this.setState(prevState => ({
            services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
        }))
    }
    

    In the input element

    this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/>

    I figured it out after some time. Thought it might help y'all :)

提交回复
热议问题