【发布时间】:2015-08-08 15:29:10
【问题描述】:
所以我正在努力进行表单验证,并且表单是使用 React.js 创建的。现在我正在寻找使用 jQuery 进行表单验证,但是当我尝试选择 react.js 创建的元素,特别是具有默认值的输入时,它表示该元素的值未定义。意味着它没有被发现。我让 jQuery 在渲染后运行,所以我不确定是什么阻止它找到 id。
index.html
<section id="formDiv" class="sections">
</section>
<script src="js/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!-- React.js -->
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<!-- Form jsx -->
<script src="comp/Form.jsx" type="text/jsx"></script>
<script src="comp/InputGroup.jsx" type="text/jsx"></script>
<script src="comp/CheckboxGroup.jsx" type="text/jsx"></script>
<script src="comp/RadioGroup.jsx" type="text/jsx"></script>
<script type="text/jsx">
React.render(<Form />, document.getElementById('formDiv'));
</script>
<script src="js/formverification.js" type="text/javascript"></script>
Form.jsx(是的,我知道 form 是个可怕的名字)
var Form = React.createClass({
render: function () {
return(
<div className="container form-border">
<h2>Enter your info to subscribe.</h2>
<form>
<InputGroup className="has-success" for="nameInput" id="nameInput" type="text" placeholder="Name" glyph="glyphicon-ok">Name</InputGroup>
<InputGroup className="has-warning" for="emailInput" id="emailInput" type="email" placeholder="Enter email" glyph="glyphicon-warning-sign">Email</InputGroup>
<InputGroup className="has-error" for="passInput" id="passInput" type="password" placeholder="Password" glyph="glyphicon-remove">Password</InputGroup>
<div className="form-group">
<label for="comments">Comments</label>
<textarea className="form-control" id="commentInput" rows="3" placeholder="Enter comments here"></textarea>
</div>
</form>
</div>
);
}
});
formverification.js
console.log($('#nameInput').val());
为什么控制台日志未定义?
编辑:
抱歉,忘记了你可能需要这个:
InputGroup.jsx
var InputGroup = React.createClass({
render: function() {
return(
<div className={this.props.className + " form-group has-feedback"}>
<label className="control-label" for={this.props.for}>{this.props.children}</label>
<input type={this.props.type} value="Hello world" className="form-control" id={this.props.id} placeholder={this.props.placeholder} />
<span className={"glyphicon " + this.props.glyph + " form-control-feedback"}></span>
</div>
);
}
});
【问题讨论】:
-
我没有使用过 react,但是如果它呈现异步,那么你的 console.log 可能会在 InputGroup 标签上运行(又名 val() 是未定义的)。尝试记录选择器而不是 val() 以查看它是否选择了您期望的内容
-
Object { context: HTMLDocument → index.html, selector: "#nameInput" } 这就是我得到的
-
我不知道这是否应该出现,不过
-
我应该尝试转换 jsx 吗?我要试试。
-
这实际上解决了它!
标签: javascript jquery html reactjs