在Reactjs中获取表单数据

 红Lisa 发布于 2023-01-17 12:06

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

render : function() {
      return (
        
); }, handleLogin: function() { //How to access email and password here ? }

我应该在handleLogin: function() { ... }访问EmailPassword字段中写什么?

9 个回答
  • 使用change输入上的事件更新组件的状态并访问它handleLogin:

    handleEmailChange: function(e) {
       this.setState({email: e.target.value});
    },
    handlePasswordChange: function(e) {
       this.setState({password: e.target.value});
    },
    render : function() {
          return (
            <form>
              <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} />
              <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/>
              <button type="button" onClick={this.handleLogin}>Login</button>
            </form>);
    },
    handleLogin: function() {
        console.log("EMail: " + this.state.email);
        console.log("Password: " + this.state.password);
    }
    

    工作小提琴:http://jsfiddle.net/kTu3a/

    另外,阅读文档,有一整节专门用于表单处理:http://facebook.github.io/react/docs/forms.html

    以前你也可以使用React的双向数据绑定帮助mixin来实现同样的目的,但现在不赞成设置值和更改处理程序(如上所述):

    var ExampleForm = React.createClass({
      mixins: [React.addons.LinkedStateMixin],
      getInitialState: function() {
        return {email: '', password: ''};
      },
      handleLogin: function() {
        console.log("EMail: " + this.state.email);
        console.log("Password: " + this.state.password);
      },
      render: function() {
        return (
          <form>
            <input type="text" valueLink={this.linkState('email')} />
            <input type="password" valueLink={this.linkState('password')} />
            <button type="button" onClick={this.handleLogin}>Login</button>
          </form>
        );
      }
    });
    

    文档在这里:http://facebook.github.io/react/docs/two-way-binding-helpers.html

    2023-01-17 12:06 回答
  • 如果您的所有输入/ textarea都有一个名称,那么您可以从event.target中过滤掉所有内容:

    onSubmit(event){
      const fields = Array.prototype.slice.call(event.target)
          .filter(el => el.name)
          .reduce((form, el) => ({
            ...form,
            [el.name]: el.value,
          }), {})
    }
    

    没有onChange方法,值,defaultValue的完全不受控制的形式......

    2023-01-17 12:06 回答
  • 另一种方法是使用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中使用单选按钮中描述的很多原因?这种方法并不总是最好的,但它确实在一些简单的情况下提供了一种有用的替代方法.

    2023-01-17 12:07 回答
  • 您可以onClick将按钮上的事件处理程序切换到onSubmit窗体上的处理程序:

    render : function() {
          return (
            <form onSubmit={this.handleLogin}>
              <input type="text" name="email" placeholder="Email" />
              <input type="password" name="password" placeholder="Password" />
              <button type="submit">Login</button>
            </form>
          );
        },
    

    然后,您可以使用FormData解析表单(并根据需要从其条目构造JSON对象).

    handleLogin: function(e) {
       const formData = new FormData(e.target)
       const user = {}
    
       e.preventDefault()
    
       for (let entry of formData.entries()) {
           user[entry[0]] = entry[1]
       }
    
       // Do what you will with the user object here
    }
    

    2023-01-17 12:07 回答
  • 处理refs的简单方法:

    class UserInfo extends React.Component {
    
      constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit(e) {
        e.preventDefault();
        
        const formData = {};
        for (const field in this.refs) {
          formData[field] = this.refs[field].value;
        }
        console.log('-->', formData);
      }
    
      render() {
        return (
            <div>
              <form onSubmit={this.handleSubmit}>
                <input ref="phone" className="phone" type='tel' name="phone"/>
                <input ref="email" className="email" type='tel' name="email"/>
                <input type="submit" value="Submit"/>
              </form>
            </div>
        );
      }
    }
    
    export default UserInfo;
    2023-01-17 12:07 回答
  • 我建议采用以下方法:

    import {Autobind} from 'es-decorators';
    
    export class Form extends Component {
    
        @Autobind
        handleChange(e) {
            this.setState({[e.target.name]: e.target.value});
        }
    
        @Autobind
        add(e) {
            e.preventDefault();
            this.collection.add(this.state);
            this.refs.form.reset();
        }
    
        shouldComponentUpdate() {
            return false;
        }
    
        render() {
            return (
                <form onSubmit={this.add} ref="form">
                    <input type="text" name="desination" onChange={this.handleChange}/>
                    <input type="date" name="startDate" onChange={this.handleChange}/>
                    <input type="date" name="endDate" onChange={this.handleChange}/>
                    <textarea name="description" onChange={this.handleChange}/>
                    <button type="submit">Add</button>
                </form>
            )
        }
    
    }
    

    2023-01-17 12:07 回答
  • 加上迈克尔·肖克的答案:

    class MyForm extends React.Component {
      constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit(event) {
        event.preventDefault();
        const data = new FormData(event.target);
    
        console.log(data.get('email')); // reference by form input's `name` tag
    
        fetch('/api/form-submit-url', {
          method: 'POST',
          body: data,
        });
      }
    
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label htmlFor="username">Enter username</label>
            <input id="username" name="username" type="text" />
    
            <label htmlFor="email">Enter your email</label>
            <input id="email" name="email" type="email" />
    
            <label htmlFor="birthdate">Enter your birth date</label>
            <input id="birthdate" name="birthdate" type="text" />
    
            <button>Send data!</button>
          </form>
        );
      }
    }
    

    参见这篇中篇文章:如何使用Just React处理表单

    仅当按下“提交”按钮时,此方法才获取表单数据。清洁得多的IMO!

    2023-01-17 12:07 回答
  • 有几种方法可以做到这一点:

    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)使用refs

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

    2023-01-17 12:07 回答
  • 同样,这也可以使用。

    handleChange: function(state,e) {
      this.setState({[state]: e.target.value});
    },
    render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleChange.bind(this, 'email')} />
          <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange.bind(this, 'password')}/>
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>
      );
    },
    handleLogin: function() {
      console.log("EMail: ", this.state.email);
      console.log("Password: ", this.state.password);
    }
    

    2023-01-17 12:07 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有