<Autosuggest
id="river"
name="river"
placeholder="Enter River Name"
onChange={this.onChange}
required="true"
data={this.props.users}
getSuggestionValue={this.getSuggestionValue.bind(this)}/>
我覺得上面的代碼會有所幫助,在getSuggestionValue,您將獲得價值,你可以用,
例如:
getSuggestionValue(value){
this.setState({ val:value}); //or anything else
}
同時提交(例如):
submitFunction(){
console.log(this.state.val); //receive value here
}
代碼變化codepen
const languages = [
{
name: 'C',
year: 1972
},
{
name: 'C#',
year: 2000
},
{
name: 'C++',
year: 1983
},
{
name: 'Clojure',
year: 2007
},
{
name: 'Elm',
year: 2012
},
{
name: 'Go',
year: 2009
},
{
name: 'Haskell',
year: 1990
},
{
name: 'Java',
year: 1995
},
{
name: 'Javascript',
year: 1995
},
{
name: 'Perl',
year: 1987
},
{
name: 'PHP',
year: 1995
},
{
name: 'Python',
year: 1991
},
{
name: 'Ruby',
year: 1995
},
{
name: 'Scala',
year: 2003
}
];
// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
function escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getSuggestions(value) {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
}
function getSuggestionValue(suggestion) {
return this.props.getValue(suggestion.name,this.props.id);
}
function renderSuggestion(suggestion) {
return (
<span>{suggestion.name}</span>
);
}
class MyAutosuggest extends React.Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (_, { newValue }) => {
const { id, onChange } = this.props;
this.setState({
value: newValue
});
onChange(id, newValue);
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested =() => {
this.setState({
suggestions: []
});
};
render() {
const { id, placeholder } = this.props;
const { value, suggestions } = this.state;
const inputProps = {
placeholder,
value,
onChange: this.onChange
};
return (
<Autosuggest
id={id}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
);
}
}
class App extends React.Component {
onChange(id, newValue) {
console.log(`${id} changed to ${newValue}`);
}
getValueForInput(val,id){
console.log(val,id);
}
render() {
return (
<div>
<MyAutosuggest
id="type-c"
placeholder="Type 'c'"
onChange={this.onChange}
getValue={this.getValueForInput.bind(this)}
/>
<MyAutosuggest
id="type-p"
placeholder="Type 'p'"
onChange={this.onChange}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
我還是不明白當我提交時我將如何得到選定的數據。 根據輸入ID,我們需要選擇所選項目。 –