如果我以如下形式使用 Ant Design TreeSelect 组件,一切都可以:
<Form.Item>
{getFieldDecorator('geo_objects_value', {
rules: [{
required: true,
message: 'Warning msg'
}],
})(
<TreeSelect
treeData={treeGeoObjects}
treeNodeFilterProp={'title'}
treeCheckable={true}
allowClear
showCheckedStrategy={SHOW_PARENT}
dropdownStyle={{maxHeight: 500, overflow: 'auto'}}
/>
)}
</Form.Item>
但是如果我尝试在 Ant Design Tree 组件中使用自定义类,它会给出警告消息:这意味着尚未收到该值。
我的自定义类:
class Demo extends React.Component {
constructor(props) {
super(props);
this.treeData = props.treeData;
this.state = {
expandedKeys: [],
autoExpandParent: true,
value: [],
};
}
onExpand = expandedKeys => {
this.setState({
expandedKeys,
autoExpandParent: false,
});
};
onCheck = value => {
this.setState({value});
this.props.value = value;
console.log('onCheck', this.props.value);
};
renderTreeNodes = data =>
data.map(item => {
if (item.children) {
return (
<TreeNode title={item.title} key={item.key} dataRef={item}>
{this.renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode key={item.key} {...item} />;
});
render() {
return (
<Tree
checkable
onExpand={this.onExpand}
expandedKeys={this.state.expandedKeys}
autoExpandParent={this.state.autoExpandParent}
onCheck={this.onCheck}
checkedKeys={this.state.value}
>
{this.renderTreeNodes(this.treeData)}
</Tree>
);
}
}
在表单中使用自定义类:
<Form.Item>
{getFieldDecorator('geo_objects_value', {
rules: [{
required: true,
message: 'Warning msg'
}],
})(
<Demo treeData={treeGeoObjects}/>
)}
</Form.Item>
我做错了什么?为什么 getFieldDecorator 无法从我的类中获取值?请帮忙!
最佳答案
使用getFieldDecorator
初始化自定义组件后,Form
无法像使用getFieldDecorator
那样控制它默认 antd
组件。
在这种情况下,开发者需要使用注入(inject)的回调并手动控制状态。
您需要使用注入(inject)了getFieldDecorator
的this.props.onChange
,请read the docs carefully .
After wrapped by
getFieldDecorator
, value (or other property defined by valuePropName) onChange (or other property defined by trigger) props will be added to form controls, the flow of form data will be handled byForm
.
关于reactjs - 将自定义类与 getFieldDecorator 结合使用(React、Ant Design),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570336/