何时使用inputRef.current而不是this.inputRef React.js?

问题描述 投票:1回答:3

我在两个语法之间感到困惑,以便从反应文档中访问引用...我想知道的是什么时候使用inputRef.current来访问引用而不是this.inputRef in react

reactjs reference
3个回答
1
投票

当使用React.creatRef()和React 16语法创建引用时,您可以使用引用的当前属性即inputRef.current来访问它。

React.createRef()

class User extends Component{
    constructor(props){
        super();
        this.nameField = React.createRef();
        this.onClick = this.focusOnNameField.bind(this);
        this.state = {
            name : props.name
        };

    }
    focusOnNameField = ()=>{
        this.nameField.current.focus();
    }

    render(){
        return(
            <div>
                <input ref={this.nameField} name="username" value={this.state.name} />
                <button onClick={this.onClick} >Fous on field</button>
            </div>
        )
    }
}

没有React.createRef()

const User = (props)=>{
    let nameField = null;


   const setRefernce = (inputElement)=>{

        this.nameField = inputElement;
    }
    const onClick = (e)=>{
        e.preventDefault();
        this.nameField.focus();
    }



    return(
        <div>
            <form onSubmit={onClick.bind(this)}>
                <input ref={setRefernce} name="username" value={props.name} />
                <button type="submit" >Focus Input</button>
            </form>

        </div>
    );
}

2
投票

正如其他答案所提到的,current ref属性是由React.createRef()创建的,最初在React 16中没有,并且在React 16.3中引入。

通常它是旧语法(React 15,React 16.0到16.2):

<input ref={ref => this.inputRef = ref}/>
...
this.inputRef.focus()

与新语法(React 16.3及更高版本):

inputRef = React.createRef();
...
<input ref={this.inputRef}/>
...
this.inputRef.current.focus()

新语法引入了一个可用的模式,可以在较旧的React版本中使用:

inputRef = { current: null };
...
<input ref={ref => this.inputRef.current = ref}/>
...
this.inputRef.current.focus()

重要的区别是React.createRef()创建了包含唯一属性current的ref对象。这是一种使ref对象引用永久化的模式,即使current属性中的ref正在改变。这样,ref对象可以通过引用传递,即使current最初是null

以前这是一个反模式,主要是因为ref是不稳定的:

const ComponentThatAcceptsRefs = ({ inputRef }) => (
  <button onClick={() => inputRef.focus() }>Focus</button>
);

<input ref={ref => this.inputRef = ref}/>
<ComponentThatAcceptsRefs inputRef={this.inputRef}/>

在这种情况下,当它作为道具传递时,它是未定义的。这需要使inputRef支持一个吸气功能,以使其工作,getInputRef={() => this.inputRef}

虽然ref对象(demo)可以做同样的事情:

const ComponentThatAcceptsRefs = ({ inputRef }) => (
  <button onClick={() => inputRef.current.focus() }>Focus</button>
);

inputRef = React.createRef();
...
<input ref={this.inputRef}/>
<ComponentThatAcceptsRefs inputRef={this.inputRef}/>

在React中可能有更多传统和实用的方法不依赖于refs,但是可以用ref对象来做到这一点。


1
投票

我相信this.ref适用于React 15,当你指定一个像这样的参考时:

ref={(input) => { this.textInput = input; }}

所以你可以使用this.textInput

对于React 16的'current'语法,在构造函数中使用this.textInput = React.createRef()然后像这样赋值:

ref={this.textInput}

所以你然后使用this.textInput.current来访问它。

虽然引用混淆的特定文档/代码的引用可能有助于清除问题。

© www.soinside.com 2019 - 2024. All rights reserved.