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

318

我有以下的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 - 有什么想法这个代码有什么问题吗?


10
this.onSubmit.bind(this) 的意思是绑定当前的 thisonSubmit 方法上。 - zerkms
好的 - 您想将其添加为答案,我会勾选它吗? - JoeTidee
4
没有绑定时,e.target.value 怎么样? - omarjmh
1
e.target.value不是指向按钮而不是输入字段吗? - JoeTidee
当点击提交按钮(即 onClick={this.onSubmit.bind(this)})时,您需要将 onSubmit 方法绑定到提交按钮(DOM 元素)。如果您想访问表单中标题输入的值,可以使用 onSubmit(event) { const title = event.target.elements.title.value; } - tim-montague
显示剩余3条评论
18个回答

2

您的错误是因为使用了class,而在使用class时我们需要绑定函数以便它能够正常工作。无论如何,有很多教程解释了为什么我们应该使用“this”,以及在JavaScript中“this”是什么。

如果您更正提交按钮,它应该可以正常工作:

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

同时,如果你想在控制台中显示该输入框的值,你应该使用 var title = this.title.value;


2
如果您想了解更多关于“this”的内容,此链接可能会有所帮助。 - Soroush Bk
https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.ab7z5tgpw - Soroush Bk

2

最简单的方法是使用箭头函数

使用箭头函数改写后的代码

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

};


1
// 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" />


虽然您的答案可能对问题有帮助,但最好还是加上一些解释。请花2分钟时间添加解释。这将改善您的答案,也方便未来的用户。 - DaFois
当然,我会做到的。 - Kidali Kevin

0

您可以在不添加“onChange”函数的情况下获取输入值。

只需将“ref属性”添加到输入元素中:

然后在需要时使用 this.refs 获取输入值。

4
不再推荐这样做。 - JoeTidee
1
你可以使用它们,但建议使用props和callbacks来保持数据流向单一方向。 - JoeTidee
最好添加一个正确添加 refs 的示例,即使用 ref 回调而不是传统的字符串。 - JoeTidee

0

如果您使用类组件,则只需要3个步骤-首先,您需要声明输入字段的状态,例如this.state = {name:''}。其次,您需要编写一个函数来设置状态,当它在下面的示例中更改时,它是setName(),最后您必须编写输入jsx,例如< input value={this.name} onChange = {this.setName}/>

import React, { Component } from 'react'

export class InputComponents extends Component {
    constructor(props) {
        super(props)

        this.state = {
             name:'',
             agree:false
        }
        this.setName = this.setName.bind(this);
        this.setAgree=this.setAgree.bind(this);
    }

    setName(e){
        e.preventDefault();
        console.log(e.target.value);
        this.setState({
            name:e.target.value
        })
    }
    setAgree(){
        this.setState({
            agree: !this.state.agree
        }, function (){
            console.log(this.state.agree);
        })
    }
    render() {
        return (
            <div>
                <input type="checkbox" checked={this.state.agree} onChange={this.setAgree}></input>
                < input value={this.state.name} onChange = {this.setName}/>
            </div>
        )
    }
}

export default InputComponents

0
export default class MyComponent extends React.Component {

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

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

};

0
将您的ref更改为:ref ='title'并删除name ='title' 然后删除var title = this.title并编写:
console.log(this.refs.title.value)

另外,您应该在 this.onSubmit 中添加 .bind(this)

(这在我的情况下起作用,我的情况相当类似,但是我使用的是 onSubmit={...} 而不是 onClick,并且它被放置在表单中(<form onSubmit={...} ></form>)


-1

使用未受控制的字段:

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        console.log(e.target.neededField.value);
    }

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

};

你的输入字段为什么有一个未使用的ref和两个name属性? - gl03

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接