1、类组件ref的字符串方式
class App extends React.Component{
componentDidMount(){
console.log("componentDidMount...",this)
this.refs.textInput.focus()
}
render(){
console.log("render...")
return (
<div>
<input ref="textInput"/>
</div>
)
}
}
2、类组件ref的回调函数方式
class App extends React.Component{
componentDidMount(){
this.textInput.focus()
}
render(){
return (
<div>
{/*直接用回调函数的方式进行挂载*/}
<input ref={el => {this.textInput = el}} />
</div>
)
}
}
3、类组件ref的createRef方式
class App extends React.Component{
constructor(props) {
super(props)
this.myRef = React.createRef() //1.创建一个ref的引用,并且可以通过this.myRef属性去进行访问
this.state = {
}
}
componentDidMount(){
//3.注意:使用current属性才可以获取到标记的元素本身
this.myRef.current.focus()
}
render(){
return (
<div>
{/*2.在组件或者dom元素上面通过ref进行标记*/}
<input ref={this.myRef}/>
</div>
)
}
}
4、函数式组件中定义ref
const App =(props)=>{
const {} =props;
//1.创建一个ref的引用对象
const inputRef = React.useRef();
const onButtonClick = ()=>{
//3. `current` 指向已挂载到 DOM 上的文本输入元素
inputRef.current.focus();
}
return (
<div>
{/*2.通过ref属性绑定dom元素*/}
<input ref={inputRef}/>
<button onClick={onButtonClick}>点击获取焦点</button>
</div>
)
}
父组件获取子组件的自定义方法
import React, { Component } from 'react';
import {Modal} from 'antd';
//父组件
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
visible:false,
}
}
handleCancel = () => {
this.setState({visible:false});
}
handleOk = () => {
//4、调用子组件的自定义方法getItemsValue。注意:通过this.formRef 才能拿到数据
console.log(this.formRef.getItemsValue());
this.handleCancel();
}
render() {
const {} = this.props;
return (
<Modal
visible={this.state.visible}
title="新增"
okText="保存"
onCancel={this.handleCancel}
onOk={this.handleOk}
>
{/*1、直接用回调函数的方式进行fromRef*/}
<Children wrappedComponentRef={form => this.formRef = form} />
</Modal>
);
}
}
export default Parent ;
import React, { Component } from 'react';
import {Form,Input} from 'antd';
const FormItem = Form.Item;
class Children extends Component{
constructor(props) {
super(props);
this.state = {}
}
getItemsValue = () =>{ //2、自定义方法,用来传递数据(需要在父组件中调用获取数据)
const valus = this.props.form.getFieldsValue(); //3、getFieldsValue:获取from表单组件值
return valus;
}
render(){
const { form } = this.props;
const { getFieldDecorator } = form;
return(
<>
<Form layout="vertical">
<FormItem label="姓名">
{getFieldDecorator('name')(
<Input />
)}
</FormItem>
<FormItem label="年龄">
{getFieldDecorator('age')(
<Input />
)}
</FormItem>
<FormItem label="城市">
{getFieldDecorator('address')(
<Input />
)}
</FormItem>
</Form>
</>
)
}
}
export default Form.create()(Children);