React createRef循环动态赋值ref问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React createRef循环动态赋值ref问题

acezhwang   2023-02-03 我要评论

React createRef循环动态赋值ref

react的refs已经是过时的API了,不适合用于循环动态赋值ref,最近又在项目中遇到需要循环动态赋值ref,这是用createRef的方法,在此记录一下,亲测有效!

handleChange = (key) => {
    this[`input${key}Ref`] = React.createRef();
}
 
handleSave = () => {
    const { list } = this.state;
    for (let item of list) {
        if (item.value && item.value.length > 100) {
          Toast.show(`${item.name}不能超过100个字符`);
          this[`input${item.key}Ref`].current&&this[`input${item.key}Ref`].current.focus();
          return;
        }
    }
    // 写接口等其他逻辑
 }
 
render() {
    const { list } = this.state;
    <div>
        {
            list.map(item=>{
              <Input
                  ref={this[`input${item.key}Ref`]}
                  value={item.value}
                  onChange={() => { this.handleChange(item.key) }}
              />
            })
        }
        <Button type="primary" onClick={this.handleSave}>保存</Button>
     </div>
}

React中ref的理解

(1) React的ref有3种用法

字符串

dom节点上使用,通过this.refs[refName]来引用真实的dom节点

<input ref="inputRef" /> //this.refs['inputRef']来访问

回调函数

React 支持给任意组件添加特殊属性。ref 属性接受一个回调函数,它在组件被加载或卸载时会立即执行。

  • 当给 HTML 元素添加 ref 属性时,ref 回调接收了底层的 DOM 元素作为参数。
  • 当给组件添加 ref 属性时,ref 回调接收当前组件实例作为参数。
  • 当组件卸载的时候,会传入null

ref 回调会在componentDidMount 或 componentDidUpdate 这些生命周期回调之前执行。

<input ref={(input) => {this.textInput = input;}} type="text" />   //HTML 元素添加 ref 属性时
<CustomInput ref={(input) => {this.textInput = input;}} />   //组件添加 ref 属性

React.createRef()

在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性

将能拿到dom节点或组件的实例

class Child extends React.Component{
    constructor(props){
        super(props);
        this.myRef=React.createRef();
    }
    componentDidMount(){
        console.log(this.myRef.current);
    }
    render(){
        return <input ref={this.myRef}/>
    }
}

(2) 根据ref获取dom

React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()返回的组件实例,但可以通过ReactDOM.findDOMNode(ref)来获取组件挂载后真正的dom节点

var Parent = React.createClass({
  render: function(){
    return (
      <div className = 'parent'>
        <Child ref = 'child'/>
      </div>
    )
  },
  componentDidMount(){
    console.log(this.refs.child); // 访问挂载在组件上ref
    console.log(ReactDOM.findDOMNode(this.refs.child)); // 访问真正的dom节点
  }
})

var Child = React.createClass({
  render: function() {
    return (
        <div ref="test">
          <a ref="update">更新</a>
        </div>
    );
  }
});

(3) react-redux使用时利用ref调用子组件方法不可用报错

在使用react的时候,我们难免会在父组件中调用子组件的方法,我们常用ref调用子组件的方法

如下在父组件中调用子组件的写法

父组件

handleShowModalAdd = () => {
    this.add.handleToggle()//handleToggle为子组件中的方法
}
<SystemAdd ref={(el) => this.add = el}/>

但是当我们在子组件中使用redux的时候,由于使用connect对子组件进行了包装,会导致获取不到子组件中的方法

下面的是使用redux后的ref使用方法

父组件

handleShowModalAdd = () => {
    this.add.handleToggle()//handleToggle为子组件中的方法
}
<SystemAdd onRef={(ref) => this.add = ref }/>

子组件

componentDidMount(){
    this.props.onRef(this)//将组件实例this传递给onRef方法
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们