React-Redux-Forms启用另一个反应组件中的复选框

时间:2017-03-09 11:15:57

标签: reactjs react-redux react-redux-form

我已经给了别人使用React-Redux-Form的React项目(这不是redux-form),并且需要在另一个React Component上启用一个基于a的复选框。在React-Redux-Form的文本框中输入值。通过defult,复选框被禁用,并且只有在存在值时才应启用。

在互联网上搜索未能找到使用的示例。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

这是一个非常粗略的例子,并不打算运行 - 只需显示如何操作的流程:

带有输入字段的组件可能包含:

  //1) this is setting a local state, when the user submits you can send it to redux so that it is available across the app.

  this._saveInputToLocal() {
    var emailRegEx = /^.+@.+\..+$/i;

    this.setState({
      email: e.target.value 
      }, function() {
    }.bind(this));
  },

 //2) when the user clicks submit - send the input to redux
 //lets assume this is saved into a property on state called `formInput`:

  this._saveInputToRedux() {
    const = { dispatch }
    dispatch(saveUserInput(this.state.email)) 
  },  


  render: function(){        
    return (
      <div className={`field email ${css(styles.emailContainer)}`}>
        <input
          type='email'
          placeholder={ 'helloworld@code.com' }
          onChange={this._saveEmailToState}
        />   
      </div>
      <button type='submit' onClick={this._saveInputToRedux}>Submit</button>
    )
  }
});

所以你看,你有一些东西:一个更新本地状态的函数,一个处理提交的函数 - 本地状态的值触发的地方,以及将该值存储在redux中的动作。不要忘记导入connect,以便在道具上使用dispatch,也不要忘记将操作导入到组件中。

现在,在具有复选框的其他组件中:

  // 3) assuming you have mapped your redux state to your props you make a function that checks for a valid input value:

  this._hasValidValue() {
    const { formInput } = this.props
    return formInput && formInput !== null && formInput !== undefined && formInput.length > 0 
  }

//here in the render you display either an enabled or disabled checkbox based on if you have a valid input from the other component. Because this is based on state, this component will re-render when state is updated (goes from invalid to valid or vice versa) 

  render: function(){ 
    return (
      <div className="checkbox">
      { hasValidValue() 
        ? <input type="checkbox" name="some-name" />
        : <input type="checkbox" name="some-name" disabled/>
      }
    )
  }
});