首页 文章

React Webpack - 提交按钮不检索表单提交的输入值

提问于
浏览
1

我正在使用带有React的webpack,我不能在生活中了解这个版本中发生了什么 . 这应该是正在发生的事情 .

  • var headerInput 更改为输入的任何值 onChange .

  • 提交表单时( onSubmit ),console.log记录 headerInput 值 .

The problem :获取控制台记录的值是数字,它是否像在handlerInput函数中一样分配了值?'s usually something like: .0.0.1. I think it' s console.log 'ing the click event. Why isn' t?

任何帮助深表感谢 . 谢谢,全部 .

var headerInput = null;

import React from "react";

export default class Navigation extends React.Component{
  handlerInput(e,headerInput){
    headerInput = e.target.value;
    console.log(headerInput);
  };
  clickSubmit(e,headerInput){
    e.preventDefault();
    console.log(headerInput);
  };
  render(){
    return(
    <form onSubmit={this.clickSubmit.bind(this)}>
      <input type="text" placeholder="change header" onChange={this.handlerInput.bind(this)} />
      <button>Change Header</button>
    </form>
    );
  }
};

2 回答

  • 1

    这不是使用React的推荐方法 . 您应该使用组件附带的状态API,而不是依赖“全局”来存储您的状态 .

    像这样:

    import React from "react";
    
    export default class Navigation extends React.Component{
      constructor(props) {
        super(props);
    
        // Set up your default state here.
        this.state = { }; 
    
        // Do early binding.
        this.handlerInput = this.handlerInput.bind(this);
        this.clickSubmit = this.clickSubmit.bind(this);
      }
    
      handlerInput(e){
        // Use setState to update the state.
        this.setState({ 
          headerInput: e.target.value
        }
      };
      clickSubmit(e){
        e.preventDefault();
    
        // You read state via this.state
        console.log(this.state.headerInput);
      };
      render(){
        return(
        <form onSubmit={this.clickSubmit}>
          /* Make sure you pass the current state to the input */
          <input 
            type="text" 
            placeholder="change header" 
            onChange={this.handlerInput} 
            value={this.state.headerInput}
          />
          <button>Change Header</button>
        </form>
        );
      }
    };
    

    我绝对建议你重温官方的反应文档,比如thinking in reactreact forms教程 .

  • 1

    如果输入是严格单向的(你只读取它),那么只需使用ref

    import React from "react";
    
    class Navigation extends React.Component{
      clickSubmit(e,headerInput){
        e.preventDefault();
        console.log(this.inputEl.value);
      };
      render(){
        return(
          <form onSubmit={this.clickSubmit.bind(this)}>
            <input placeholder="change header" ref={el => this.inputEl = el} />
            <button>Change Header</button>
          </form>
        );
      }
    };
    

    注意...

    尽管不推荐使用字符串引用,但它们被认为是遗留的,并且可能在将来的某个时候被弃用 . 回调引用是首选 .

    https://facebook.github.io/react/docs/more-about-refs.html

相关问题