我从React.js开始,我想做一个简单的表单,但在文档中我找到了两种方法.
在第一种是使用参考文献:
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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
和第二个是使用状态的阵营部件内部:
var TodoTextInput = …Run Code Online (Sandbox Code Playgroud) 我不知道我是否正确地执行此操作...如果我想从输入中获取值,我使用this.refs.whatever.value.trim()但是如果该输入是无状态函数组件,我该怎么办检索onSubmit的值?
我知道在研究之后现在这是不正确的,但是你应该如何从这些输入字段中获得价值呢?
import React, {Component} from 'react'
import {InputField} from '../components/forms/InputField'
import {Button} from '../components/forms/Button'
export default class SignupWrapper extends Component {
_handleSubmit(e) {
e.preventDefault();
const email = this.refs.email.value.trim();
const password = this.refs.password.value.trim();
const confirm = this.refs.confirm.value.trim();
console.log({email, password, confirm});
}
render() {
return (
<form id="application-signup" onSubmit={this._handleSubmit.bind(this)}>
<InputField type={'email'} name={'email'} text={'email'}
helpBlock={'email is required'} ref="email" />
<InputField type={'password'} name={'password'} text={'password'}
helpBlock={'password is required'} ref="password" />
<InputField type={'password'} name={'confirm'} text={'confirm password'}
helpBlock={'password confirmation is required'} ref="confirm" />
<Button type={'submit'} className={'btn …Run Code Online (Sandbox Code Playgroud) im trying to use a ref for focusing on the element when onBlur. I'm using react v.16.9.0 My code is this:
const handleKeyDown = (e, element, index) => {
element.current.focus();
event.preventDefault();
};
const pinDigitBuilder = () => {
const arr = Array(...Array(TOTAL_PIN_DIGITS));
return arr.map((x, i) => {
const inputRef = useRef(null);
console.log(inputRef);
return (
<Field
key={`${PIN_DIGIT}${i + 1}`}
id={`${PIN_DIGIT}${i + 1}`}
name={`${PIN_DIGIT}${i + 1}`}
ref={inputRef}
component={InputTextField}
className="text xxs2"
classNameInvalid="text xxs2 error"
type="text"
divClassName="fieldWrap"
maxLength={1}
normalize={keepNumbersOnly}
errorStyle={{ display: 'none' }}
autoComplete="off" …Run Code Online (Sandbox Code Playgroud)