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

t9aqgxwy  于 2023-01-02  发布在  React
关注(0)|答案(6)|浏览(137)

我试图在输入框为空时禁用一个按钮。在React中对此最好的方法是什么?
我正在做类似下面的事情:

<input ref="email"/>

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

是这样吗?
这不仅仅是动态属性的复制,因为我对从一个元素到另一个元素的数据传输/检查也很感兴趣。

ehxuflar

ehxuflar1#

您需要将输入的当前值保留在state中(或传递其值up to a parent via a callback functionsideways〈此处为您的应用的状态管理解决方案〉 的更改,以便最终将其作为prop传回组件),以便为按钮派生禁用的prop。
使用状态示例:

<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>
oyxsuwqo

oyxsuwqo2#

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

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>
vptzau2j

vptzau2j3#

另一种检查方法是内联函数,这样每次渲染(每次 prop 和状态更改)时都会检查条件

const isDisabled = () => 
  // condition check

这是可行的:

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

但这行不通:

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

isr3a4wc4#

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;
zfycwa2u

zfycwa2u5#

<button disabled={false}>button WORKS</button>
<button disabled={true}>button DOES NOT work</button>

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

dba5bblo

dba5bblo6#

它的简单让我们假设您已经通过扩展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/>
            )

       }

   }

相关问题