gpt4 book ai didi

reactjs - 在 ReactJS 中获取表单数据

转载 作者:IT老高 更新时间:2023-10-28 11:10:18 25 4
gpt4 key购买 nike

我的 render 函数中有一个简单的表单,如下所示:

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() { ... } 中写什么来访问 EmailPassword 字段?

最佳答案

有几种方法可以做到这一点:

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>
)
}
}

关于reactjs - 在 ReactJS 中获取表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com