如何在React.js中实现文本字段控件 使用以下两个功能之一通过关键字获取标签列表。请勿修改提供的功能。
function getLabels(keyword) {
const allLabels = ['NextActions', 'Someday_Actions', 'Costco', 'Alexa'];
const result = allLabels
.filter(function(x) {
return x.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
});
return result;
}
// or this synchronous api
function getLabelsAsync(keyword) {
const result = getLabels(keyword);
const delay = Math.random() * 800 + 200; // delay 200~1000ms
return new Promise(function(resolve, reject) {
setTimeout(resolve, delay, result);
});
}
答案 0 :(得分:0)
您必须实现一个受控组件才能做到这一点。您需要将组件状态附加到输入的值,并创建一个方法来处理用户在其上输入的每个字符。
此处有更多详细信息:https://reactjs.org/docs/forms.html#controlled-components
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}