如何重置按钮的值以点击反应

时间:2018-01-15 01:23:11

标签: reactjs

鉴于以下代码,我在努力弄清楚如何在点击一次后将按钮的值设置回原始状态?

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

/**
 * links : https://www.youtube.com/watch?v=GhbhD1HR5vk&t=297s
 * https://reactjs.org/docs/handling-events.html
 * 
 * 
 * 
 */
class Input extends Component {

    constructor(props) {
        super(props);

        this.state = { 
            tagged: false,
            user: '', 
            tag: ''
        }

       this.handleUserChange = this.handleUserChange.bind(this);
    }

    handleClick(e) {
        this.setState({tagged: true});
        e.preventDefault();
        console.log('The link was clicked.');
    }

    handleUserChange(e) {
       console.log("e.target.value");
       this.setState({user: e.target.value});
    }

    handleTagChange(e) {
        console.log(e.target.value);
        this.setState({tag: e.target.value});
     }

    render() {                                                
        return (
            <div id="id" style={divStyle}>
                <p> hello </p>
                <input
                    style = {textStyle}
                    placeholder="user@email.com" 
                    type="text"
                    onChange={ this.handleUserChange.bind(this) } 
                >
                </input>

                <input
                    style = {textStyle}
                    placeholder="tag" 
                    type="text"
                    onChange={ (e) => this.handleTagChange(e) }
                >
                </input>
                <button
                    onClick={(e) => this.handleClick(e)}
                    style={buttonStyle}>
                    {this.state.tagged ? 'Tagged' : 'Tag ' } 
                </button>

                <p>
                    {this.state.tagged ? this.state.user + ' was tagged with ' + this.state.tag : ''}
                    {/* {this.setState({tagged: false})} */}
                </p>
            </div>    
        )
    }
}

var divStyle = {
    position: 'relative',
    top:'50%',
    left: '15%',
};

var textStyle = {
    margin: '20px 20px 20px 20px',
    height: '20px',
    width: '200px',
};

var buttonStyle = {
    margin: '20px 20px 20px 20px',
    background: '#7FFFD4',
    color: 'black',
    height: '25px',
    width: '250px'
};  

export default Input;

1 个答案:

答案 0 :(得分:0)

在handClick方法中设置你的状态

this.setState((prevState)=> ({
      tagged: !prevState.tagged
 }));