繁体   English   中英

如何检查以确保在 React 中单击按钮时填写表单?

[英]How do I check to make sure the form is filled on button click in React?

我有一个按钮,它根据用户提供的数字进行计算并将结果填充到页面中。 相同的按钮还将产品保存到数据库,同时还使用数据库中的相同产品直观地填充页面。 所以基本上它显示了用户在字段中输入的任何内容的总数和以前的总数。 我的问题是我想包含错误处理,以便如果数字是 0 或 NaN,因为它们没有填满所有 forms,它会引发警报并且也不会将数据推送到数据库。 这是我的尝试,但它不起作用,如果结果是 NaN 它仍然显示它并将 NaN 值推送到数据库,我该如何实现? 尝试如下:

handleClick = (event, billInfo) => {
event.preventDefault();
const dbRef = firebase.database().ref();

const result =
  (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

// ATTEMPT START ======

result === NaN
  ? alert("Please fill all forms!")
  : dbRef.push({
      result: result.toFixed(2),
      name: billInfo.name,
    });

// ATTEMPT END ======

this.setState({
  total: result.toFixed(2),
});

这是带有链接到主 app.js 的按钮的表单组件:

class inputForm extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      group: "",
      amount: "",
      tip: "",
    };
  }

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  clearForm = (event) => {
    event.preventDefault();

    this.setState({
      name: "",
      group: "",
      amount: "",
      tip: "",
    });
  };

  render() {
    return (
      <form className="tipApp">
        <div>
          <label htmlFor="groupName">
            <i class="fas fa-id-card"></i>Group Name?
          </label>
          <input
            onChange={this.handleChange}
            type="text"
            id="groupName"
            value={this.state.name}
            placeholder="Name your group"
            name="name"
          />
        </div>

        <div>
          <label htmlFor="groupSize">
            <i class="fas fa-users"></i>How many?
          </label>
          <input
            onChange={this.handleChange}
            type="number"
            id="groupSize"
            value={this.state.group}
            min="1"
            step="1"
            placeholder="Add the group size"
            name="group"
            required
          />
        </div>

        <div>
          <label htmlFor="billAmount">
            <i class="fas fa-receipt"></i>How much?
          </label>
          <input
            onChange={this.handleChange}
            type="number"
            id="billAmount"
            value={this.state.amount}
            min="0"
            step=".01"
            placeholder="Add the bill total"
            name="amount"
            required
          />
        </div>

        <div>
          <label htmlFor="tipAmount">
            <i class="fas fa-heart"></i>Tip?
          </label>
          <input
            onChange={this.handleChange}
            type="number"
            id="tipAmount"
            value={this.state.tip}
            min="10"
            step="5"
            placeholder="Add the tip %"
            name="tip"
          />
        </div>

        <button onClick={(event) => this.props.getTotal(event, this.state)}>
          Split it!
        </button>
        <button onClick={this.clearForm}>Reset</button>
      </form>
    );
  }
}

这是我试图错误处理的完整 app.js 主文件:

class App extends Component {
  constructor() {
    super();
    this.state = {
      bills: [],
      total: 0,
    };
  }

  componentDidMount() {
    const dbRef = firebase.database().ref();

    // Event listener that watches the database
    dbRef.on("value", (snapshot) => {
      const firebaseData = snapshot.val();

      const billData = [];

      for (const bill in firebaseData) {
        billData.push({
          id: bill,
          name: firebaseData[bill].name,
          value: firebaseData[bill].result,
        });
      }
      this.setState({
        bills: billData,
      });
    });
  }

  handleClick = (event, billInfo) => {
    event.preventDefault();
    const dbRef = firebase.database().ref();

    const result =
      (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

    result === NaN
      ? alert("Please fill all forms!")
      : dbRef.push({
          result: result.toFixed(2),
          name: billInfo.name,
        });

    this.setState({
      total: result.toFixed(2),
    });
  };

  deleteBill = (billId) => {
    const dbRef = firebase.database().ref();

    dbRef.child(billId).remove();
  };

  render() {
    return (
      <div className="wrapper">
        <h1 className="logoName">Spl|tr</h1>
        <h3>Bill Splitting App</h3>

        <Form getTotal={this.handleClick} />
        <h2>${this.state.total}</h2>

        <h3>Previous Bills</h3>
        <Bills receipts={this.state.bills} delete={this.deleteBill} />
      </div>
    );
  }
}

这是 Bills.js 组件,它使用按钮单击表单下方的先前项目填充页面:

const Bills = (props) => {
  return (
    <ul>
      {props.receipts.map((bill) => {
        return (
          <li key={bill.id}>
            <p>{bill.name}</p>
            <p>${bill.value}</p>
            <button onClick={() => props.delete(bill.id)}>
              <i class="fas fa-times-circle"></i>
            </button>
          </li>
        );
      })}
    </ul>
  );
};

无论结果是否有效,您的处理程序都会更新 state。 一个小的重构应该允许一个有效的结果并推送到 DB 并更新 state一个无效的结果和警报。 0NaN都是错误值,因此您可以简单地检查result是否为真/假。

handleClick = (event, billInfo) => {
  event.preventDefault();
  const dbRef = firebase.database().ref();

  const result =
    (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

  if (result) {
    dbRef.push({
      result: result.toFixed(2),
      name: billInfo.name,
    });
    this.setState({
      total: result.toFixed(2),
    });
  } else {
    alert("Please fill all forms!")
  }
};

编辑 how-do-i-check-to-make-sure-the-form-is-filled-on-button-click-in-react

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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