所以我正在做表单验证,表单是使用 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>
);
}
});
表单验证.js
console.log($('#nameInput').val());
为什么控制台日志未定义?
编辑:
抱歉,忘了您可能需要这个:
输入组.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>
);
}
});
最佳答案
找到问题了! JSX Transformer 实在是太慢了,无法及时加载内容以供 jQuery 找到它。将 jsx 编译成 js 解决了这个问题,现在弹出正确的值。
关于javascript - 为什么 jQuery 找不到这个 react.js 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467322/