反应js输入复选框组

时间:2017-03-28 04:48:38

标签: reactjs

是否可以在react中创建输入复选框?如果我已经映射了3个复选框,并且只能单击一个复选框。我只是给每个人一个状态,当一个人被选中时,然后取消选中其他状态吗?

我已经尝试过无线电输入,但是我需要能够将它们全部取消选中,就像在一个广播组中一样,一旦你选择了一个我无法完全取消它们。

3 个答案:

答案 0 :(得分:1)

此类行为最好由Redux等库管理。使用Redux,您可以使用一个reducer来独立跟踪每个复选框的状态,同时仍然了解整个复选框组的状态。

例如,您可以使用一个带有render()方法的组件,该方法从Redux存储中派生checked属性。

    render() {

        // grab the checked attribute from your Redux store
        // typically, you access the store via props using Provider
        // pass each checkbox an id from the parent, and use this as a key
        // to find its checked value in the store
        let checked = this.props.store[this.props.checkboxId];

        <input id={this.props.checkboxId} className='checkbox' type='checkbox' onChange={this.onChangeHandler} checked={checked} />
        <label className='checkboxLabel' htmlFor={this.props.checkboxId}>{this.props.text}</label>
    }

您的商店和减速机看起来像这样:

    const initialState = {
         checkbox1: false,
         checkbox2: false,
         checkbox3: false
    };

    const store = (state = initialState, action) => {
        switch (action.type) {
             case ('UPDATE_CHECKBOX'):
                 switch (action.payload.checkboxId) {
                     case 'checkbox1':
                         return Object.assign({}, state, {
                         checkbox1: action.payload.checked
                     });
                     case 'checkbox2':
                         return Object.assign({}, state, {
                         checkbox2: action.payload.checked
                     });
                     case 'checkbox3':
                         return Object.assign({}, state, {
                         checkbox3: action.payload.checked
                     });
                     default:
                         return state;
             default:
                 return state;
    }

然后在你的组件中,onChangeHandler只调度一个动作,指示reducer更新复选框组状态。

    onChangeHandler(event) {

        // grab the id of the checkbox you want to update
        let checkboxToUpdate = event.target.id;

        // set the checked value to be the opposite of what it was
        let checked = !this.props.store[event.target.id];

        // dispatch an action to perform the update
        this.props.dispatch(checkboxActions.updateCheckbox({ checkboxId: checkboxToUpdate, checked }));

     }

这种方法的好处在于,如果单击另一个复选框,则可以触发checked属性以在一个复选框中更改。例如,如果我们改变我们的reducer:

    const store = (state = initialState, action) => {
        switch (action.type) {
             case ('UPDATE_CHECKBOX'):
                 switch (action.payload.checkboxId) {
                     case 'checkbox1':
                         return Object.assign({}, state, {
                         checkbox1: action.payload.checked,
                         checkbox2: true,
                         checkbox3: false
                     });
                     case 'checkbox2':
                         return Object.assign({}, state, {
                         checkbox2: action.payload.checked
                     });
                     case 'checkbox3':
                         return Object.assign({}, state, {
                         checkbox3: action.payload.checked
                     });
                     default:
                         return state;
             case 'CLEAR_CHECKBOXES':
                 return Object.assign({}, state, {
                     checkbox1: false,
                     checkbox2: false,
                     checkbox3: false
                  });
             default:
                 return state;
    }

这里我们点击checkbox1时调度'UPDATE_CHECKBOX',将checkbox2设置为true表示其checked属性,checkbox3设置为false。从本质上讲,我们控制一个复选框的行为,点击另一个!您还可以执行一项操作,将所有checkboes的已检查属性设置为false,如上面的CLEAR_CHECKBOXES。我在这里省略了大部分动作和动作类型的设置,但是Redux文档很好地指导了你如何设置它。希望这有帮助!

答案 1 :(得分:0)

为单选按钮创建单独的组件。

DEMO:https://jsfiddle.net/69z2wepo/74970/

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {

       Fragment  fragment = new ProductActivity(); // Change fragment class name to ProductFragment

       FragmentManager fragmentManager = getSupportFragmentManager();
       fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }
    .........
    ..............
}

CSS:

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
    this.childs = [{checked:false},{checked:false},]

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(val,index) {  
  this.childs.forEach((data)=>{
  data.checked = false;
  })
        this.childs[index].checked=val;
    this.setState({})
  }

  render() {
  console.log(this.childs,"this.childs")

    return (
    <div>
       {
        this.childs.map((val,i)=>{
         return  <Child key ={i} index={i} checked={val.checked} handleChange={this.handleInputChange}/> 

        })
       }

    </div>
    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
   this.handleChange = this.handleChange.bind(this);
   }
   handleChange(event){
     var value = event.target.value;
         if(this.props.checked=='on'){
      value = false;
     }
     console.log(value);
     this.props.handleChange(value,this.props.index)
   }

    render() {
  return (
  <div>
    <input
            name="test"
            type="radio"
            checked={this.props.checked}
            onChange={this.handleChange} />
            </div>
  )
 }
}


ReactDOM.render(
  <Reservation />,
  document.getElementById('root')
);

答案 2 :(得分:0)

在一个新的Jsfiddle中,从上面修复。 https://jsfiddle.net/SPiara/m3xL2mqm/3/

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {  
        let checked= this.state.checked;
    this.setState({checked:!checked})
  }

  render() {
    return (
    <div>
      <Child checked={this.state.checked} givenName={'Ram'} handleChange={this.handleInputChange}/>         
      <Child checked={this.state.checked} givenName={'Sham'} handleChange={this.handleInputChange}/>
    </div>
    );
  }
}

class Child extends React.Component {
    render() {
  return (
  <div>
    <label htmlFor={this.props.givenName}>{this.props.givenName}</label>
    <input
      name="test"
      id={this.props.givenName}
      type="radio"
      defaultValue='checked'
      value={this.props.checked}
      onChange={this.props.handleChange} />
    </div>
  )
 }
}

ReactDOM.render(
  <Reservation />,
  document.getElementById('root')
);