问题描述
我是 React 的新手.当输入字段为空时,我试图禁用按钮.React 中最好的方法是什么?
我正在做类似以下的事情:
<button disabled={!this.refs.email}>让我进来</button>
这是正确的吗?
这不仅仅是动态属性的重复,因为我也很好奇将数据从一个元素传输/检查到另一个元素.
您需要将输入的当前值保持在状态(或传递其值的变化 通过回调函数传给父级,或sideways,或<您的应用程序的状态管理解决方案在这里>,以便它最终作为道具传递回您的组件),以便您可以为按钮派生禁用道具.
使用状态的示例:
<script src="https://fb.me/react-0.13.3.js"></script><script src="https://fb.me/JSXTransformer-0.13.3.js"></script><div id="应用程序"></div><script type="text/jsx;harmony=true">void function() { "use strict";var App = React.createClass({getInitialState() {返回{电子邮件:''}},句柄变化(e){this.setState({email: e.target.value})},使成为() {返回 <input name="email" value={this.state.email} onChange={this.handleChange}/><button type="button" disabled={!this.state.email}>Button</button>}})React.render(, document.getElementById('app'))}()
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:
<input ref="email"/>
<button disabled={!this.refs.email}>Let me in</button>
Is this correct?
It's not just duplication of the dynamic attribute, because I'm also curious about transferring/checking the data from one element to another.
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<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>
这篇关于当输入为空时如何禁用按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!