我目前在我的React项目中使用Twitter Typeahead,我想显示基于Typeahead的建议,但我无法设法让它发挥作用。
在我的代码下面:
var Search = React.createClass({
getInitialState: function () {
return {query: ''};
},
handleChange: function (e) {
this.setState({query: e.target.value});
},
componentDidMount(){
var suggestions = {
query: "d",
results: [
{name: "first"},
{name: "second"},
{name: "third"},
{name: "fourth"}
]
};
var suggests = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
local: suggestions
});
var template = _.template('<span class="name"><%= name %></span>');
$(React.findDOMNode(this.refs.suggestion)).typeahead({
hint: true,
highlight: true,
},
{
name: 'suggests',
displayKey: 'name',
source: suggests.ttAdapter(),
templates: {
suggestion: function (data) {
return template(data);
}
}
});
},
render() {
<form action="myAction" method="GET">
<input name="q" id="query" ref="suggestion" className="form-control suggestions" type="text"
value={this.state.query}
onChange={this.handleChange} onBlur={this.handleChange}/>
</form>
}
});
根据我的代码,我需要添加或更改哪些内容才能获得自动完成功能&amp;关于我的项目的建议。非常感谢您的宝贵意见和建议。帮助
答案 0 :(得分:7)
缺少以下内容
var Search = React.createClass({
getInitialState: function() {
return {
query: ''
};
},
handleChange: function(e) {
this.setState({
query: e.target.value
});
},
componentDidMount: function() {
var suggestions = {
query: "d",
results: [{
name: "first"
}, {
name: "second"
}, {
name: "third"
}, {
name: "fourth"
}]
};
var suggests = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
local: suggestions.results
});
suggests.initialize(); // <----- THIS ONE
var template = _.template('<span class="name"><%= name %></span>');
$(React.findDOMNode(this.refs.suggestion)).typeahead({
hint: true,
highlight: true,
}, {
name: 'suggests',
displayKey: 'name',
source: suggests.ttAdapter(),
templates: {
suggestion: function(data) {
return template(data);
}
}
});
},
render: function() { // <---- MISSING A RETURN HERE
return (<form action="myAction" method="GET">
<input name="q" id="query" ref="suggestion" className="form-control suggestions" type="text"
value={this.state.query}
onChange={this.handleChange} onBlur={this.handleChange}/>
</form>);
}
});