我正在尝试将react-autosuggest集成到redux表单中。我可以确认我的Autosuggest组件在没有从redux-form传递到Field组件时工作正常,但是当我将它传递给组件属性时,我可以键入一个字母,然后控件变得没有响应但是,我看到没有错误我的控制台。
我已经尝试过为我的组件使用包装器,如下所示:https://github.com/moroshko/react-autosuggest/issues/250
我对它的理解是包装器获取Field传递给组件的属性,并以它所需的方式将它们传递给Autosuggest。
下面的MyForm.js中是否有我遗漏或误解的内容?请注意,我已删除了redux操作以尝试简化我的问题。
import React, {Component} from 'react'
import {Field, reduxForm} from 'redux-form'
import FormDataViewer from './FormDataViewer'
import Autosuggest from 'react-autosuggest'
const options = [
{value: "Apple", display:"Apple"},
{value: "Banana", display:"Banana"},
{value: "Cbataloupe", display:"Cbataloupe"},
{value: "Damson", display:"Damson"}
]
const getSuggestions = value => {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
return inputLength === 0 ? [] : options.filter(fruit =>
fruit.display.toLowerCase().slice(0, inputLength) === inputValue
);
};
const getSuggestionValue = suggestion => suggestion.display;
const renderSuggestion = suggestion => (
<div>
{suggestion.display}
</div>
);
class MyForm extends Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render(){
const { value, suggestions } = this.state;
const inputProps = {
placeholder: 'start type a fruit',
value,
onChange: this.onChange
};
const required = value => (value ? undefined : 'Requires an answer')
const AutoSuggestWrapper = ({input, suggestions, onSuggestionsFetchRequested, onSuggestionsClearRequested, renderSuggestion, inputProps, meta: {touched, error},...custom}) => (
<div>
<Autosuggest
getSuggestionValue = {(suggestion) => {
input.onChange(suggestion.value);
return suggestion.display;
}}
suggestions={suggestions}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
{touched && (error && <div className="error"><i className="glyphicon glyphicon-info-sign"></i> {error}</div>)}
</div>
)
return (
<div>
<form>
<label>AutoComplete</label><br />
<Field name={'AutoComplete'}
component={AutoSuggestWrapper}
className="form-control"
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
validate={required}/>
</form>
<FormDataViewer />
</div>
)
}
}
export default reduxForm({
form: 'quoteForm',
destroyOnUnmount: false,
forceUnregisterOnUnmount: true
})(MyForm)
注意:FormDataViewer只是将redux状态输出为json字符串,因此我可以调试