How to disable a button when an input is empty?

前端 未结 4 1649
心在旅途
心在旅途 2020-12-07 13:09

I\'m new to React. I\'m trying to disable a button when an input field is empty. What is the best approach in React for this?

I\'m doing something like the following:

4条回答
  •  情书的邮戳
    2020-12-07 13:13

    Using constants allows to combine multiple fields for verification:

    class LoginFrm extends React.Component {
      constructor() {
        super();
        this.state = {
          email: '',
          password: '',
        };
      }
      
      handleEmailChange = (evt) => {
        this.setState({ email: evt.target.value });
      }
      
      handlePasswordChange = (evt) => {
        this.setState({ password: evt.target.value });
      }
      
      handleSubmit = () => {
        const { email, password } = this.state;
        alert(`Welcome ${email} password: ${password}`);
      }
      
      render() {
        const { email, password } = this.state;
        const enabled =
              email.length > 0 &&
              password.length > 0;
        return (
          
    ) } } ReactDOM.render(, document.body);
    
    
    
    
    
    

提交回复
热议问题