项目中遇到的 ref 几种情况下的使用记录
一、函数组件 (1) <Form>组件中:ref={ref => (FormRef = ref)}
import React, { useRef } from 'react';
import { Input, Form, Row, Col } from 'antd';
const { TextArea } = Input;
const Delete = props => {
let FormRef = useRef();
const saveData = () => {
console.log(FormRef);
}
props.modalControl.registerOk(() => saveData());
return (
<Form
ref={ref => (FormRef = ref)}
>
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={24} sm={24}>
<Form.Item
label="删除原因"
name="desc"
>
<TextArea placeholder="请输入" rows={4} />
</Form.Item>
</Col>
</Row>
</Form>
)
}
export default Delete
console.log(FormRef) (等同于) <Form>组件中:form={form}
import React, { useRef } from 'react';
import { Input, Form, Row, Col } from 'antd';
const { TextArea } = Input;
const Delete = props => {
const [form] = Form.useForm();
const saveData = () => {
console.log(form);
}
props.modalControl.registerOk(() => saveData());
return (
<Form
form={form}
>
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={24} sm={24}>
<Form.Item
label="删除原因"
name="desc"
>
<TextArea placeholder="请输入" rows={4} />
</Form.Item>
</Col>
</Row>
</Form>
)
}
export default Delete
console.log(form) :效果同上
(2)组件<Input> 上的ref
import React, { useRef } from 'react';
import { Input, Form, Row, Col } from 'antd';
const { TextArea } = Input;
const Delete = props => {
let FormRef = useRef();
const saveData = () => {
console.log(FormRef);
}
props.modalControl.registerOk(() => saveData());
return (
<Input ref={FormRef} />
)
}
export default Delete
console.log(FormRef) : 返回值和上面的不一样,而且外层多了一个current 二、类组件 使用React.createRef() 方法
import React, { Component, Fragment } from 'react';
class Interface extends Component{
constructor(props) {
super(props);
this.proTableRef = React.createRef();
console.log(this.proTableRef)
}
render(){
return(
<> </>
)
}
}
例如,像页面刷新需求的时候就可以使用this.proTableRef.current.reload() 方法…
|