2016-12-23 64 views
1

後不改變值I有一個大的形式與被動態地從一個get請求呈現各種形式的元件。所有其他類型的表單(如文本和選擇)工作正常,但複選框不是。ReactJs複選框第一使用

後,我檢查了一次,只停留在(即使我取消的話),我這麼想是錯在這裏做什麼?

這是我目前的相關代碼:

class Input extends Component{ 
    render(){ 
     var form; 
     if (this.props.componentClass=="choice") { 
      // select form 
     } 

     else if (this.props.componentClass=="bool") 
      form =(<Checkbox id={this.props.controlId} onChange={this.props.onChange} 
           defaultChecked={this.props.placeholder} > 
         </Checkbox>); 
     else 
      // text form 
     return (
      <div> 
       <Form inline onSubmit={this.handleSubmit}> 
        <FormGroup controlId={this.props.controlId}> 
         <ControlLabel>{this.props.name}</ControlLabel> 
         {form} 
         <Panel> 
         {this.props.description} 
         </Panel> 
         <FormControl.Feedback /> 
        </FormGroup> 
       </Form> 
       <br/> 
      </div> 
     ); 
    } 
} 

// onChange code (comes from a parent component) 
    onChange(e){ 
     const form = Object.assign({}, this.state.form); 
     form[e.target.id] = e.target.value; 
     this.setState({ form }); 
     console.log('current state: ', this.state); 
    } 

回答

1

正如前面所說的,您必須綁定的onChange功能,但你應該使用「檢查」,而不是「價值」。

這裏就是你們的榜樣修改是這樣的:

https://jsfiddle.net/8d3of0e7/3/

class Input extends React.Component{ 

    constructor(props){ 
    super(props) 
    this.state = {form:{}} 
    } 

    render(){ 
    var form; 
    if (this.props.componentClass=="choice") { 
     // select form 
    }else if (this.props.componentClass=="bool"){ 
     form = (
     <ReactBootstrap.Checkbox 
      id={this.props.controlId} 
      onChange={this.props.onChange.bind(this)} 
      checked={this.state.form[this.props.controlId]} 
      defaultChecked={this.props.placeholder} > 
     </ReactBootstrap.Checkbox>); 
    }else{ 
     // text form 
    } 
    return (
     <div> 
     <ReactBootstrap.Form inline onSubmit={this.handleSubmit}> 
      <ReactBootstrap.FormGroup controlId={this.props.controlId}> 
      <ReactBootstrap.ControlLabel> 
       {this.props.name} 
      </ReactBootstrap.ControlLabel> 
      {form} 
      <ReactBootstrap.Panel> 
       {this.props.description} 
      </ReactBootstrap.Panel> 
      <ReactBootstrap.FormControl.Feedback /> 
      </ReactBootstrap.FormGroup> 
     </ReactBootstrap.Form> 
     <br/> 
     </div> 
    ); 
    } 

    componentDidUpdate(){ 
    console.log('current state: ', this.state); 
    } 

} 

function onChange(e) { 
    const form = Object.assign({}, this.state.form); 
    form[e.target.id] = e.target.checked; 
    this.setState({ form }); 
} 

ReactDOM.render(
    <Input componentClass='bool' controlId='retired' 
    name='Is retired?' onChange={onChange}/>, 
    document.getElementById('root') 
) 

在這個例子中我們的國家將是:狀態:{形式:{退役:真正}}

+1

完美。謝謝! – theJuls

1

的問題是,你給的複選框一個onchange不綁定到一個值。爲此,最初的檢查工作,因爲這是該defaultChecked爲你做的,但一旦你真正與它進行交互,你有沒有國家勢必會使它反應在勾選或者不定位它重新呈現。