如何在React.js中禁用按钮 [英] How to disable button in React.js
问题描述
我有这个组件:
import React from 'react';
export default class AddItem extends React.Component {
add() {
this.props.onButtonClick(this.input.value);
this.input.value = '';
}
render() {
return (
<div className="add-item">
<input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
<button disabled={!this.input.value} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
</div>
);
}
}
我希望按钮被禁用当输入值为空时。但上面的代码不起作用。它说:
I want the button to be disabled when input value is empty. But the code above doesn't work. It says:
add-item.component.js:78 Uncaught TypeError:无法读取未定义的属性'value'
add-item.component.js:78 Uncaught TypeError: Cannot read property 'value' of undefined
指向 disabled = {!this.input.value}
。我在这里做错了什么?我猜测,当执行 render
方法时,可能还没有创建ref。如果,那么什么是workararound?
pointing to disabled={!this.input.value}
. What can I be doing wrong here? I'm guessing that perhaps ref isn't created yet when render
method is executed. If, so what is the workararound?
推荐答案
使用 refs
不是最佳实践是因为它直接读取DOM,最好使用React的状态
。此外,您的按钮不会更改,因为组件未重新呈现并保持其初始状态。
Using refs
is not best practice because it reads the DOM directly, it's better to use React's state
instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
您可以使用 setState
与 onChange
事件监听器一起在每次输入字段更改时再次呈现组件:
You can use setState
together with an onChange
event listener to render the component again every time the input field changes:
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
以下是一个有效的例子:
Here's a working example:
class AddItem extends React.Component {
constructor() {
super();
this.state = { value: '' };
this.onChange = this.onChange.bind(this);
this.add = this.add.bind(this);
}
add() {
this.props.onButtonClick(this.state.value);
this.setState({ value: '' });
}
onChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<div className="add-item">
<input
type="text"
className="add-item__input"
value={this.state.value}
onChange={this.onChange}
placeholder={this.props.placeholder}
/>
<button
disabled={!this.state.value}
className="add-item__button"
onClick={this.add}
>
Add
</button>
</div>
);
}
}
ReactDOM.render(
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,
document.getElementById('View')
);
<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>
<div id='View'></div>
这篇关于如何在React.js中禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!