如何使用ReactJS获取输入字段的值?

JavaScript

LEY古一阿飞

2020-03-11

我有以下React组件:

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        var title = this.title;
        console.log(title);
    }

    render(){
        return (
            ...
            <form className="form-horizontal">
                ...
                <input type="text" className="form-control" ref={(c) => this.title = c} name="title" />
                ...
            </form>
            ...
            <button type="button" onClick={this.onSubmit} className="btn">Save</button>
            ...
        );
    }

};

控制台给了我undefined-任何想法这段代码有什么问题吗?

第613篇《如何使用ReactJS获取输入字段的值?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
null 2020.03.11
// On the state
constructor() {
  this.state = {
   email: ''
 }
}

// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}

<Input 
  value={this.state.email ? this.state.email : ''} 
  onChange={event => this.setState({ email: event.target.value)}
  type="text" 
  name="emailAddress" 
  placeholder="johdoe@somewhere.com" />

斯丁A 2020.03.11

您的错误是因为您使用了类,并且在使用类时,我们需要使用This绑定函数才能正常工作。无论如何,有很多教程为什么我们应该在JavaScript中执行“ this”和“ this”是什么。

如果您更正提交按钮,则应该可以:

<button type="button" onClick={this.onSubmit.bind(this)} className="btn">Save</button>

并且如果您想在控制台中显示该输入的值,则应该使用var title = this.title.value;。

Gil米亚 2020.03.11

通过将“ this”绑定到函数updateInputValue(evt),我成功地做到了

this.updateInputValue = this.updateInputValue.bind(this);

但是,输入值= {this.state.inputValue} ...并不是一个好主意。

这是babel ES6的完整代码:

class InputField extends React.Component{


  constructor(props){
   super(props);
   //this.state={inputfield: "no value"};   
   this.handleClick = this.handleClick.bind(this);
   this.updateInputValue = this.updateInputValue.bind(this);
  }

  handleClick(){
   console.log("trying to add picture url");
   console.log("value of input field : "+this.state.inputfield);

  }

  updateInputValue(evt){
    //console.log("input field updated with "+evt.target.value);
    this.state={inputfield: evt.target.value};   

  }

  render(){
    var r; 
    r=<div><input type="text" id="addpixinputfield" 
            onChange={this.updateInputValue} />
      <input type="button" value="add" id="addpix" onClick={this.handleClick}/>
      </div>;    
    return r;
   }
}
谷若汐 2020.03.11

在反应16中,我使用

<Input id="number" 
       type="time" 
       onChange={(evt) => { console.log(evt.target.value); }} />
猿前端前端 2020.03.11

你应该在类MyComponent下使用构造函数扩展React.Component

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

然后您将获得标题的结果

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android