react中的onClick函数不适用于条件句

时间:2018-12-07 13:01:41

标签: reactjs

我对“ onClick”功能为什么不起作用有疑问?当我按下按钮时,它只会收到“您还不够大!”。我使用输入字段。

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;

2 个答案:

答案 0 :(得分:1)

如果您要在点击时验证输入,请以状态存储输入的值。

( |$)

答案 1 :(得分:0)

您可以为输入创建一个处理程序,然后单击按钮从状态中获取值。 看看我的方法。

class App扩展了React.Component {     状态= {         年龄:空,         术语:“写一个数字”     }

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

}