首先,如果在给定列表中退出,您需要找到并提取适当的子字符串(您正在寻找的字符串),并通过提取该子字符串来制作自定义字符串,如下所示。
//autoValue - value you are looking for
//main - item value
const val =
main.slice(0, main.indexOf(autoValue)) +
"<b>" +
autoValue +
"</b>" +
main.slice(
main.indexOf(autoValue) + autoValue.length,
main.length
);
现在,您必须将dangerouslySetInnerHTML 用于span 或任何自定义HTML 组件,用于呈现自动完成组件中的每个项目。
这是完整的示例。
const items = [
"React",
"Angular",
"Vue",
"Node",
"Express",
"PHP",
"Laravel",
"Material",
"CSS",
"HTML"
];
function ListItem(props) {
if (props.value.indexOf(props.autoValue) > -1 && props.autoValue.length > 0) {
const main = props.value;
const val =
main.slice(0, main.indexOf(props.autoValue)) +
"<b>" +
props.autoValue +
"</b>" +
main.slice(
main.indexOf(props.autoValue) + props.autoValue.length,
main.length
);
return (
<div>
<span dangerouslySetInnerHTML={{ __html: val }} />
<hr />
</div>
);
} else {
return (
<span>
{props.value}
<hr />
</span>
);
}
}
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map(number => (
<ListItem
key={number.toString()}
value={number}
autoValue={props.autoValue}
/>
));
return <div>{listItems}</div>;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ""
};
this.update = this.update.bind(this);
}
update(e) {
e.preventDefault();
this.setState({ inputValue: e.target.value });
}
render() {
return (
<div>
<input
type="text"
onChange={this.update}
name="inputValue"
value={this.state.inputValue}
/>
<NumberList numbers={items} autoValue={this.state.inputValue} />
<span> {this.state.inputValue} </span>
</div>
);
}
}
export default App;
工作示例。 https://codesandbox.io/s/n9n65wqj5j