码迷,mamicode.com
首页 > 其他好文 > 详细

AntDesign getFieldDecorator 获取自定义组件的值

时间:2019-06-04 19:30:07      阅读:417      评论:0      收藏:0      [点我收藏+]

标签:隐式   als   form   自定义组件   get   efault   content   let   foreach   

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那样显示的传入。

AntDesign getFieldDecorator 获取自定义组件的值

标签:隐式   als   form   自定义组件   get   efault   content   let   foreach   

原文地址:https://www.cnblogs.com/tian874540961/p/10975409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!