如何在 ReactJS 中设置'antd'表单中表单项的引用?



使用类似的方法,当我使用反应引导表单时,能够在 Form.Control 中获取所需的引用

但是在 ReactJS 中使用 antd 表单时没有获得引用

<Form.Item>        
<Input placeholder='Name' size='large'  ref="usernameref"  />
</Form.Item>

无法在其他地方访问此引用,例如单击表单内的按钮

下面的整个代码

import React from "react";
//import { Modal, Form ,Button } from "react-bootstrap";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { addUser, updateUser, loadoff, loadon} from "../actions/action.js";
import { Button, Form, Modal ,Input } from "antd";
class UserModalWindow extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
update: this.props.update,
rowindex: this.props.rowindextoupdate
};
}

static getDerivedStateFromProps(props, state) {
return { rowindex: props.rowindextoupdate };
}
render() {
async function wait(duration = 2000) {
await new Promise(resolve => setTimeout(resolve, duration));
}

const layout = {
labelCol: { span: 24 },
wrapperCol: { span: 24 },
};
return (
<Modal   {...this.props}  title="User Form" >
<Form
{...this.props}
{...this.layout}
name="basic"
>
<Form.Item
label='Name'
name='name'
rules={[{ required: true, message: 'Please input your name' }]}>
<Input placeholder='Name' size='large'  ref="usernameref"  />
</Form.Item>
<Form.Item
label='Email'
name='email'
rules={[
{
type: 'email',
message: 'The input is not valid mail.',
},
{
required: true,
message: 'Please input your mail id',
},
]}>
<Input placeholder='Email' size='large' ref="usermailref"/>
</Form.Item>

<Button  loading={this.props.loader.loading}  onClick = {async()=>
{
var obj = {}
obj.field1 = this.refs.usernameref.value ;  // here both the refs are undefined
obj.field2 = this.refs.usermailref.value;
console.log(this.refs)
this.props.loadon();
await wait();
this.props.loadoff();
if(this.state.update === 'true')
{
obj.index = this.state.rowindex.index ;
this.props.updateUser(obj);
}
else
{
console.log(obj)
this.props.addUser(obj);
}
this.props.onHide();
}}
> Save</Button>
</Form>
</Modal>
);
}
}
function mapStateToProps(state) {
return {
loader: state.loader
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ addUser, updateUser, loadon, loadoff }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserModalWindow);

但是使用 React-bootstrap Forms 可以按预期工作 可能是什么原因?我需要使用装饰字段吗?

你应该给 ref 给表单标签 请按照以下说明操作

1(像这样创建引用formRef = React.createRef(); 2(像这样在表单标签中使用此引用<Form ref={this.formRef} name="control-ref">code goes here.........</Form>

比你可以使用这个参考,你也可以检查antd文档它将如何工作 https://ant.design/components/form/如果您遇到问题或发现它有帮助,请回复此线程

最新更新