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

How to disable a button when an input is empty?

我是 React 新手。我试图在输入字段为空时禁用按钮。 React 对此的最佳方法是什么?

我正在做类似以下的事情:

<input ref="email"/>

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

这是正确的吗?

不仅仅是动态属性的重复,因为我也很好奇transferring/checking从一个元素到另一个元素的数据。

您需要将输入的当前值保持在状态中(或传递其值的更改 up to a parent via a callback function, or sideways,或 <您的应用的状态管理解决方案在此处> 这样它最终会作为道具传递回您的组件),因此您可以为按钮派生禁用的道具。

使用状态的示例:

<meta charset="UTF-8">
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<div id="app"></div>
<script type="text/jsx;harmony=true">void function() { "use strict";

var App = React.createClass({
  getInitialState() {
    return {email: ''}
  },
  handleChange(e) {
    this.setState({email: e.target.value})
  },
  render() {
    return <div>
      <input name="email" value={this.state.email} onChange={this.handleChange}/>
      <button type="button" disabled={!this.state.email}>Button</button>
    </div>
  }
})

React.render(<App/>, document.getElementById('app'))

}()</script>

使用常量允许组合多个字段进行验证:

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>

很简单,让我们假设您通过扩展包含以下内容的组件使状态完整 class

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/>
            )

       }

   }

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

const isDisabled = () => 
  // condition check

这个有效:

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

但这行不通:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>
<button disabled={false}>button WORKS</button>
<button disabled={true}>button DOES NOT work</button>

现在只需使用 useState 或任何其他条件将 true/false 传递到按钮中,假设您使用的是 React。

const Example = () => {
  
const [value, setValue] = React.useState("");

function handleChange(e) {
    setValue(e.target.value);
  }

return (


<input ref="email" value={value} onChange={handleChange}/>
<button disabled={!value}>Let me in</button> 

);

}
 
export default Example;