【问题标题】:redux get input text valueredux 获取输入文本值
【发布时间】:2017-03-24 02:40:06
【问题描述】:

我有以下 reactjs 组件。

class Login extends Component {

render() {
    if (this.props.session.Authenticated) {
        return (
            <div></div>
        );
    }
    return (
        <div>
            <input type="text" placeholder="Username" />
            <input type="password" placeholder="Password" />
            <input
                type="button"
                value="Login"
                onClick={() => this.props.LoginAction("admin", "password")}
             />
        </div>
    );
}
}

Login 组件使用了一个通过 redux 设置的 prop,名为“session.Authenticated”。如果用户会话未通过身份验证,我会提供几个input 字段(一个用于用户名,另一个用于密码)和一个Login 按钮。如果我按下Login 按钮,我想发出一个带有用户名和密码值的操作,作为参数传递。现在,如何获取参数的两个input 字段的值?

IOW,我想用两个input 字段的值删除上面代码中硬编码的“管理员,密码”。如何做到这一点?

所有示例都指向redux-form,这是我不想添加的新依赖项。我想保持我的依赖最小化,所以在我的项目中只使用 react、redux 和 react-redux。

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    类似这样的:

      class Login extends Component {
         constructor(props){
            super(props);
            this.state = {
               model = {
                  login: "",
                  password: ""
               }
            }
         }
      render() {
          if (this.props.session.Authenticated) {
            return null;
        }
        return (
            <div>
                <input type="text" value={this.state.model.value.login} onChange={e => this.updateModel(e.target.value, 'login')}placeholder="Username" />
                <input type="password" value={this.state.model.password }onChange={e => this.updateModel(e.target.value, 'password')} placeholder="Password" />
                <input
                    type="button"
                    value="Login"
                    onClick={() => this.props.LoginAction(this.state.model.login, this.state.model.password)}
                 />
            </div>
        );
    }
    
     updateModel(value, name){
        var model = extend({}, this.state.model);
        model[name] = value;
        this.setState({model});
      }
    }
    

    【讨论】:

    • 我正在使用 redux,因此需要全局维护状态。在 redux 中拥有特定于组件的状态不是一种不好的做法吗?
    • 你的 updateModel 方法应该触发动作并且动作应该更新存储值
    • React 需要大量样板代码,因此,请尝试在一些库中搜索表单。绝对可以肯定,您会发现表单组件将在其中执行所有更新魔法form 组件。
    • 我想过在输入的 onChange 事件期间发出一个动作。但对于一个简单的动作来说,这是一个很糟糕的样板。有一个 react-form 库,但我试图最小化依赖关系。似乎是不可能的。谢谢。
    • 一年前我开始从事基于反应的大型项目,并尝试了一些组件,但没有任何东西可以满足我的所有要求。最后,我为表单编写了自己的库,对所有 props.children 使用 React.cloneComponent,并且它需要最少的样板代码。不幸的是,在 clone child 之后,''ref' 属性没有按预期工作。但是如果您有兴趣,我可以分享代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2018-03-03
    相关资源
    最近更新 更多