【发布时间】:2015-06-12 17:39:54
【问题描述】:
我从 React.js 开始,我想做一个简单的表单,但在文档中我发现了两种方法。
first one 正在使用 Refs:
var CommentForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var text = React.findDOMNode(this.refs.text).value.trim();
if (!text || !author) {
return;
}
// TODO: send request to the server
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.text).value = '';
return;
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input type="text" placeholder="Say something..." ref="text" />
<input type="submit" value="Post" />
</form>
);
}
});
second one 在 React 组件中使用 state:
var TodoTextInput = React.createClass({
getInitialState: function() {
return {
value: this.props.value || ''
};
},
render: function() /*object*/ {
return (
<input className={this.props.className}
id={this.props.id}
placeholder={this.props.placeholder}
onBlur={this._save}
value={this.state.value}
/>
);
},
_save: function() {
this.props.onSave(this.state.value);
this.setState({value: ''
});
});
如果有的话,我看不出这两种选择的优缺点。 谢谢。
【问题讨论】:
-
我在这里遗漏了什么吗?为什么不使用事件对象来获取表单值?这似乎是首先在这里使用表格的唯一原因。如果您没有使用默认提交行为并且在输入上有引用,则不需要将它们包装在表单中。
标签: reactjs