AntDesign getFieldDecorator 獲取自定義組件的值
1.自定義或第三方的表單控件,也可以與 Form 組件一起使用。只要該組件遵循以下的約定:
(1)提供受控屬性 value 或其它與 valuePropName 的值同名的屬性。
(2)提供 onChange 事件或 trigger 的值同名的事件。
(3)不能是函數式組件。
2.創建組件
這里通過自定義的搜索輸入框來展示
let timeout;
let currentValue;
function fetch(value, callback) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
currentValue = value;
function getData() {
const params = {
size: 10,
name: value
};
apiSubwayList(params).then(
d => {
if (currentValue === value) {
const result = d.list;
const data = [];
result.forEach(r => {
data.push({
value: r.subwayId,
text: r.name,
});
});
callback(data);
}
}
);
}
timeout = setTimeout(getData, 300);
}
class SearchInput extends PureComponent {
state = {
data: [],
value: undefined
};
handleSearch = value => {
fetch(value, data => this.setState({data}));
};
handleChange = value => {
this.setState({value});
this.props.onChange(value)
};
render() {
const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
return (
<div>
<Select
showSearch
value={this.state.value}
placeholder={this.props.placeholder}
// style={this.props.style}
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onSearch={this.handleSearch}
onChange={this.handleChange}
notFoundContent={null}
>
{options}
</Select>
<span>輸入並選擇對應選項,否則無效</span>
</div>
)
}
}
SearchInput.propTypes = {
data: PropTypes.array,
value: PropTypes.string,
onChange: PropTypes.func
};
export default SearchInput;
可以看到,使用getFieldDecorator時,會通過props的形式向自定義的組件傳入onChange回調方法,使用這個回調函數會通知getFieldDecorator所綁定字段的值的變化。
3.使用組件
<FormItem
{...formItemLayout}
label={<span>所在地鐵站</span>}
>
{getFieldDecorator('owner', {
rules: [{
required: true,
message: '請選擇所在地鐵站',
},
],
})(
<SearchInput placeholder="輸入並選擇所屬地鐵"/>)}
</FormItem>
使用getFieldDecorator會隱式的傳入onChange回調方法,當然,如果想傳入其他參數,也可以像placeholder那樣顯示的傳入。