我在渲染函数中有一个简单的表单,如下所示:
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
},
handleLogin: function() {
//How to access email and password here ?
}
我应该在我的handleLogin: function(){…}访问电子邮件和密码字段?
这是最简单的方法
const formValidator = (form) => {
let returnData = {}
console.log(form.length);
for (let i = 0; i < form.length; i++) {
const data = form[i]
if (data.name != null && data.name != "") {
returnData[data.name] = data.value;
}
}
return returnData
}
在形式上
<form onSubmit={(e) => {
e.preventDefault()
let data = formValidator(e.currentTarget)
}}>
<RoundTextFiled name='app-id' style={{ marginTop: '10px', borderRadius: '20px' }} label="App id" fullWidth required />
<RoundTextFiled name='api-hash' style={{ marginTop: '5px' }} label="Api hash" fullWidth required />
<RoundTextFiled name='channel-id' style={{ marginTop: '5px' }} label="Channel id" fullWidth required />
<Button type='submit' variant="contained" fullWidth style={{ padding: '10px', marginTop: '5px', borderRadius: '10px' }}>Login</Button>
</form>
有几种方法可以做到这一点:
1)通过索引从数组的表单元素中获取值
handleSubmit = (event) => {
event.preventDefault();
console.log(event.target[0].value)
}
2)在html中使用name属性
handleSubmit = (event) => {
event.preventDefault();
console.log(event.target.elements.username.value) // from elements property
console.log(event.target.username.value) // or directly
}
<input type="text" name="username"/>
3)使用裁判
handleSubmit = (event) => {
console.log(this.inputNode.value)
}
<input type="text" name="username" ref={node => (this.inputNode = node)}/>
完整的示例
class NameForm extends React.Component {
handleSubmit = (event) => {
event.preventDefault()
console.log(event.target[0].value)
console.log(event.target.elements.username.value)
console.log(event.target.username.value)
console.log(this.inputNode.value)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
type="text"
name="username"
ref={node => (this.inputNode = node)}
/>
</label>
<button type="submit">Submit</button>
</form>
)
}
}
另一种方法是使用ref属性并使用this.refs引用值。这里有一个简单的例子:
render: function() {
return (<form onSubmit={this.submitForm}>
<input ref="theInput" />
</form>);
},
submitForm: function(e) {
e.preventDefault();
alert(React.findDOMNode(this.refs.theInput).value);
}
更多信息可以在React文档中找到:
https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
关于如何在React中使用单选按钮中描述的很多原因?这种方法并不总是最好的,但在一些简单的情况下确实是一种有用的替代方法。