从文本框中获取文本反应js

时间:2017-01-30 16:54:28

标签: javascript reactjs

我正在尝试使用ReactJS从文本框中获取输入但不确定如何

import React from 'react'

class component extends React.Component {
    constructor() {
          super()
          this.state = {
          word: String('')

   }
  }

 increment() {
     this.setState({
     word: this.state.word += ''
 })
}

render() {
    return (
        <div>
            <p>The message is: { this.state.word } </p>
            <input type="text" value={this.state.word} onChange={(event) =>this.handleChange(event.target.value)} />
            <input type="submit" value="Add Word" onClick={() => this.increment()} />
            {/*<p><input type="button" value="clear msg" onClick={() => this.eraseWord()} /></p>*/}
        </div>

  )
 }
}

文本框中的文本应添加到消息中:

2 个答案:

答案 0 :(得分:2)

您需要两个state个变量,一个将存储textfield的当前值,另一个将存储完整的值,而increment方法内附加textfield值来完成值并再次将其设置为'',试试这个:

class HelloWidget extends React.Component {
    constructor() {
        super();
        this.state = {
            word: '',
            new: '',
        };
    }

    increment() {
        this.setState({
            word: this.state.word + this.state.new,
            new: '',
        })
    }

    handleChange(value) {
        this.setState({
            new: value
        });
    }

    render() {
        return (
            <div>
                <p>The message is: { this.state.word } </p>
                <input type="text" value={this.state.new} onChange={(e) =>this.handleChange(e.target.value)} />
                <input type="submit" value="Add Word" onClick={() => this.increment()} />
            </div>
        );
    }
}

检查jsfiddle是否有工作示例:https://jsfiddle.net/hse607rr/

答案 1 :(得分:0)

您需要添加handleChange方法:

class component extends React.Component {
    constructor() {
        super()

        this.state = {
            word: ''
        };
    }

    increment() {
        this.setState({
            word: this.state.word + ''
        })
    }

    handleChange(value) {
        this.setState({
            word: value
        });
    }

    render() {
        return (
            <div>
                <p>The message is: { this.state.word } </p>
                <input type="text" value={this.state.word} onChange={(event) =>this.handleChange(event.target.value)} />
                <input type="submit" value="Add Word" onClick={() => this.increment()} />
                {/*<p><input type="button" value="clear msg" onClick={() => this.eraseWord()} /></p>*/}
            </div>
        );
    }
}