简体   繁体   中英

onClick function in react does`t work with conditionals

I have a question about why does not the "onClick" function work? It will only receive "You are not old enough!", when i hit the button. I use a input field.

import React, { Component } from 'react';



class App extends Component {
   constructor() {
    super();
     this.state= {
      term: 'write a number'
      }
     this.change = this.change.bind(this);
    }

   change = (event) => {
    this.setState({term: event.target.value >= 18 ? <p>You are old enough! 
  </p> : <p>You are not old enough!</p>});
  }

   render() {

     return (
       <div style={{textAlign : "center"}}>
       <input type="text"></input><br></br>
        <p>Result</p><br></br>
        {this.state.term}
        <button type="submit" onClick={this.change}>Submit</button>
      </div>
    );
  }
}

export default App;

If you want to validate the input on click, store the value of the input in state.

class App extends Component {
  constructor() {
    super();
    this.state = {
      term: 'write a number',
      value: ''
    };
  }

  handleChange = event => {
    this.setState({
      value: event.target.value
    });
  };

  validate = () => {
    this.setState({
      term:
        parseInt(this.state.value) >= 18
          ? 'You are old enough!'
          : 'You are not old enough!'
    });
  };

  render() {
    return (
      <div style={{ textAlign: 'center' }}>
        <input
          type="text"
          onChange={this.handleChange}
          value={this.state.value}
        />
        <br />
        <p>Result</p>
        <br />
        <p>{this.state.term}</p>
        <button type="submit" onClick={this.validate}>
          Submit
        </button>
      </div>
    );
  }

}

You can create a handler for the input and when you click in the button you get the value from the state. Check it out my approach.

class App extends React.Component { state = { age: null, term: 'write a number' }

onClick = () => {
    if(this.state.age) {
        const output = this.state.age >= 18 ? 
            <p>You are old enough!</p> :
            <p>You are not old enough!</p>
    this.setState({
        term: output
    });
}

onInputHandler = (event) => {
    this.setState({age: event.target.value})
}

render() {
    return (
        <div style={{textAlign : "center"}}>
            <input type="text" onChange={e => this.onInputHandler(e)}></input><br></br>
        <p>Result</p><br></br>
        <button onClick={this.onClick}>Submit</button>
        </div>);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM