【发布时间】:2019-08-21 18:42:57
【问题描述】:
我有一个自定义的自动完成功能,所以当您输入时,它会根据输入值显示一个建议列表。在列表中,我想将与输入值相同的字符加粗。
因此,如果我有一个建议列表:“alligator”、“lima”、“lime”,并且我输入了“li”,那么建议将如下所示:
- alli鳄鱼
- 里妈
- 李我
我的 jsx 文件中有这个简单的 map:
<ul>
{matches.map(function(match, idx){
let re = new RegExp(value, 'g');
let str = match.replace(re, '<b>'+ value +'</b>');
return <li key={idx}>{str}</li>
})}
</ul>
其中value 是输入值。它以这种字符串格式显示列表
- alli鳄鱼
- lima
- li我
不确定如何使用 React。我曾想过使用dangerouslyinnerhtml 或类似的东西,但我认为这是不得已而为之的事情。如果可能的话,我想避免这种情况。
这是我的自动完成组件:
class Autocomplete extends Component{
constructor(props){
super(props);
this.state = {
value: '',
matches: [],
showMatches: false
}
}
searchListing(){
api.call {
that.setState({
showMatches: true,
matches: a
});
})
}
}
handleOnChangeInput(e){
let value = e.target.value;
this.setState({ value: value})
if(value !== ''){
this.searchListing(e);
}else{
// console.log("value", e.target.value);
this.setState({
showMatches: false,
matches: []
})
}
}
render(){
let matches = this.state.matches;
let value = this.state.value;
let matchesHtml;
if(this.state.showMatches){
matchesHtml = <ul>
{matches.map(function(match, idx){
let re = new RegExp(value, 'g');
let str = match.replace(re, '<b>'+ value +'</b>');
return <li key={idx} dangerouslySetInnerHTML={{__html: str}}></li>
})}
</ul>
}
return(
<div>
<input placeholder="type a name" onChange={this.handleOnChangeInput}/>
{matchesHtml}
</div>
);
}
}
【问题讨论】:
-
在反应中也是一样的,你如何在反应中显示自动填充的数据?您可以将这个
ui > li作为子组件附加到您的组件中
标签: javascript reactjs