输入为空时如何禁用按钮?

我是React.js的新手,如果问题对您来说太愚蠢了,对不起。

我正在尝试在输入字段为空时禁用按钮。为此,React中的野兽方法是什么?

我正在执行以下操作:

<input ref="email"/>

<button disabled={!this.refs.email}>Let me in</button>

它是否正确?

这不只是动态属性的重复,因为我还很好奇将数据从一个元素传输/检查到另一个元素。

Mandy猴子2020/03/11 12:16:03

另一种检查方法是内联函数,以便在每个渲染中检查条件(每个道具和状态改变)

const isDisabled = () => 
  // condition check

这有效:

<button
  type="button"
  disabled={this.isDisabled()}
>
  Let Me In
</button>

但这不起作用:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>
Green猿古一2020/03/11 12:16:03

使用常量可以组合多个字段进行验证:

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 (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          placeholder="Email"
          value={this.state.email}
          onChange={this.handleEmailChange}
        />
        
        <input
          type="password"
          placeholder="Password"
          value={this.state.password}
          onChange={this.handlePasswordChange}
        />
        <button disabled={!enabled}>Login</button>
      </form>
    )
  }
}

ReactDOM.render(<LoginFrm />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>


</body>

斯丁ProJinJin2020/03/11 12:16:03

它很简单,我们假设您通过扩展Component使其包含一个完整的状态,该Component包含以下内容

class DisableButton extends Components 
   {

      constructor()
       {
         super();
         // now set the initial state of button enable and disable to be false
          this.state = {isEnable: false }
       }

  // this function checks the length and make button to be enable by updating the state
     handleButtonEnable(event)
       {
         const value = this.target.value;
         if(value.length > 0 )
        {
          // set the state of isEnable to be true to make the button to be enable
          this.setState({isEnable : true})
        }


       }

      // in render you having button and input 
     render() 
       {
          return (
             <div>
                <input
                   placeholder={"ANY_PLACEHOLDER"}
                   onChange={this.handleChangePassword}

                  />

               <button 
               onClick ={this.someFunction}
               disabled = {this.state.isEnable} 
              /> 

             <div/>
            )

       }

   }