【问题标题】:Trigger the React-Bootstrap Input Component Validation Programmatically以编程方式触发 React-Bootstrap 输入组件验证
【发布时间】:2014-12-03 19:24:08
【问题描述】:

我对反应很陌生,所以这可能是一件很容易的事情。我目前正在开发一个模态组件(来自 ReactBootstrap),并且我在模态对话框组件中使用 react-bootstrap 输入组件,type=email。这样,当在 <form> 元素内并提交表单时,将触发验证,如果验证失败,则会在输入组件顶部显示弹出类型消息。但是,我没有在 <form> 元素中使用此组件,并且希望在单击按钮时触发此组件。这是我拥有的代表问题的一段工作代码:

/** @jsx React.DOM */

var Modal = ReactBootstrap.Modal;
var ModalTrigger = ReactBootstrap.ModalTrigger;
var Button = ReactBootstrap.Button;
var Input = ReactBootstrap.Input;

var TheModal = React.createClass({
    handleSubmit: function() {
        // I want to trigger the email input validation here
        // via this.refs.theInput
    },
    render: function() {
        return (
            <Modal {...this.props} title="Modal Title" animation={true} closeButton={false}>
                <div className="modal-body">
                    <Input ref="theInput" type="email" label="Email Address" defaultValue="Enter email" />
                </div>

                <div className="modal-footer">
                    <Button bsStyle="primary" onClick={this.handleSubmit}>Send</Button>
                    <Button bsStyle="danger" onClick={this.props.onRequestHide}>Close</Button>

                </div>
            </Modal>
        );
    }
});

var App = React.createClass({
    render: function() {
        return (
            <div>
                <ModalTrigger modal={<TheModal />}>
                    <Button bsStyle="primary" bsSize="large">Trigger Modal</Button>
                </ModalTrigger>
            </div>
        );
    }
});

React.render( <App />,
    document.getElementById('content')
);

【问题讨论】:

    标签: twitter-bootstrap reactjs react-jsx react-bootstrap


    【解决方案1】:

    直接在 Input 上调用getValue() 函数。

    this.refs.theInput.getValue() 应该返回您的 theInput 值。

    如果可以避免的话,不要使用getDOMNode(),因为它假定底层 DOM 实现在未来的版本中不会改变。查看 react-bootstrap Input.jsx 文件了解其他功能。

    【讨论】:

      【解决方案2】:

      您的onClick 事件已连接到handleSubmit(),看起来没问题。

      通过this.refs.theInput.getDOMNode().value 访问电子邮件值在handleSubmit() 中不起作用吗?

      如果是这样,我想知道 ReactBootstrap 的 &lt;Input&gt; 是否将原生 DOM &lt;input&gt; 包装在其他一些元素中;您可能必须导航 DOM 树才能到达实际的 &lt;input&gt; 以从中获取电子邮件值。

      【讨论】:

        【解决方案3】:

        就像彼得提到的那样,我必须将物体穿过很远。

        在我的组件的渲染函数中;

        render: function() {
          return (
            <form onSubmit={this.handleSubmit}>
              <Input ref='gameTitle' type='text' buttonAfter={<Button type="submit">Save</Button>} />
            </form>
          );
        }
        

        在我的 handleSubmit 函数中;

        handleSubmit: function() {
          console.log(this.refs.gameTitle.refs.input.getDOMNode().value);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-09
          • 1970-01-01
          • 2021-08-14
          • 2012-01-25
          • 1970-01-01
          • 1970-01-01
          • 2017-10-08
          • 2022-11-12
          相关资源
          最近更新 更多