javascript - 如何在 React.js 中实现文本字段控件
问题描述
如何使用以下两个函数之一在 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);
});
}
解决方案
您必须实现一个受控组件才能做到这一点。您需要将组件状态附加到输入的值并创建一个方法来处理用户在其上输入的每个字符。
更多细节在这里:https ://reactjs.org/docs/forms.html#control-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>
);
}
}
推荐阅读
- sql - SQL删除多个表中的多行数据
- c++ - C++ 代码在不同操作系统上的编译方式不同
- azure - Asp.net 应用程序部署在托管在 DMZ NIC 上的 IIS 服务器上,无法从服务结构应用程序获得响应
- mysql - sql内部连接超过2个表和聚合函数
- php - 在 centos 上安装 nagios 时出现冲突错误
- batch-file - 计算数组中(pid)变量的数量?
- xamarin - 当我有 Xamarin 模板绑定时,是否始终需要 Source={x:Reference this}?
- css - 如何修复我的幻灯片,它一直在加载而不在 Android 上显示图片
- sql-server - SQL Server:有条件地执行查询
- css - 确定在使用 -webkit-line-clamp 进行多行省略号时是否显示省略号