【问题标题】:Getting value of input in React and checking it在 React 中获取输入的值并检查它
【发布时间】:2023-03-06 08:47:01
【问题描述】:

我有一个输入字段和一个按钮。我想这样做,如果用户在单击按钮时在输入字段中输入一个数字值,则应该出现一个带有信息的 div。现在,当单击按钮时,它会加载我的数据,但即使输入为空,它也可以工作。我怎样才能正确地从输入中获取值,检查它是否是一个数字,如果它确实是一个数字,那么 div 应该显示信息,这是我到目前为止所做的:

class CardCheck extends Component {
  constructor(props) {
    super(props);
    this.state = { showMessage: false };
  }

_checkValue() {
  if (evt.taget.value != number) {
    this.setState(prevState => ({
      showMessage: !prevState.showMessage
    }));
  } else {
    alert("Your card id can consist only of numbers!")
  }
}

  _showMessage = () =>
    this.setState(prevState => ({
      showMessage: !prevState.showMessage
    }));
  render() {
    return (
      <div>
        <div className="newsletter-container">
          <h1>Enter the ID of your card:</h1>
          <div className="center">
            <input type="number" onChange={(evt) => { console.log(evt.target.value)}} />
            <input type="submit" value="Check" onClick={this._showMessage {this._checkValue} />
          </div>
          <div />
          {this.state.showMessage && (
            <div className="results">
              <h2 className="green-heading">Your card is valid in the following places:</h2>
              <p>Magic Auto Spa</p>
              <p>Ivans auto shop</p>
              <p>AutoHouse Sofia</p>
              <p>Bankya Auto Palace</p>
              <button className="close" onClick={this._showMessage}>
                Close
              </button>
            </div>
          )}
        </div>
        <h1>Offers:</h1>
      </div>
    );
  }
}

export default CardCheck; 

我尝试使用 onChange 事件获取值,使用 if 语句检查它的类型并将该事件作为第二个 onClick 附加,但它不起作用

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您的代码中有错字:

    _checkValue() {
      if (evt.taget.value != number) {
      // -------^ should be target
    

    另外,Number.isNaN 将是更可靠的比较。

    【讨论】:

      【解决方案2】:

      首先,你有一个错误
      &lt;input type="submit" value="Check" onClick={this._showMessage{this._checkValue} /&gt;
      接下来,
      &lt;input&gt; React 中的 Boxes 的工作方式略有不同。 Check out this link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多