(1)提供受控屬性 value 或其它與 valuePropName 的值同名的屬性。api
(2)提供 onChange 事件或 trigger 的值同名的事件。antd
(3)不能是函數式組件。antdesign
這裏經過自定義的搜索輸入框來展現函數
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所綁定字段的值的變化。fetch
<FormItem {...formItemLayout} label={<span>所在地鐵站</span>} > {getFieldDecorator('owner', { rules: [{ required: true, message: '請選擇所在地鐵站', }, ], })( <SearchInput placeholder="輸入並選擇所屬地鐵"/>)} </FormItem>
使用getFieldDecorator會隱式的傳入onChange回調方法,固然,若是想傳入其餘參數,也能夠像placeholder那樣顯示的傳入。ui