我正在尝试在 onClick
之后清除我的输入字段事件。
我正在使用 react-bootstrap
库,同时有一个 getValue()
方法,没有setValue(value)
方法。
我偶然发现了这个 discussion .
我不完全理解他们的建议,以便在提交后简单地清理表单。
毕竟,如果我使用简单的 HTML <input>
而不是 react-bootstrap
我可以通过元素 ref
获取节点并将其值设置为空字符串或其他内容。
什么被认为是清理我的 react Bootstrap 的 react 方式 <Input />
元素?
最佳答案
将状态存储在 React 组件中,通过 props 设置元素值,通过事件回调获取元素值。这是一个例子:
这是直接取自其文档的示例。我刚刚添加了一个 clearInput()
方法来向您展示您可以通过更新组件的状态来清除输入。这将触发重新渲染,从而导致输入值更新。
const ExampleInput = React.createClass({
getInitialState() {
return {
value: ''
};
},
validationState() {
let length = this.state.value.length;
if (length > 10) return 'success';
else if (length > 5) return 'warning';
else if (length > 0) return 'error';
},
handleChange() {
// This could also be done using ReactLink:
// http://facebook.github.io/react/docs/two-way-binding-helpers.html
this.setState({
value: this.refs.input.getValue()
});
},
// Example of how you can clear the input by just updating your state
clearInput() {
this.setState({ value: "" });
},
render() {
return (
<Input
type="text"
value={this.state.value}
placeholder="Enter text"
label="Working example with validation"
help="Validation is based on string length."
bsStyle={this.validationState()}
hasFeedback
ref="input"
groupClassName="group-class"
labelClassName="label-class"
onChange={this.handleChange} />
);
}
});
关于javascript - react-bootstrap:清除元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068392/