如何在 React JS 中获取可重用组件中的引用

how to get ref's in reusable component in react js

大家好,我是 React js 的小蜜蜂。我有一个具有 ref 属性 的可重用组件。当我将 _ref 道具值传递给 Reusablecomponent 时。我没有得到正确的 ref 值。我在下面的代码中模拟了相同的内容(我在可重用组件中收到了什么价值)。

可重用组件

     class A extends React.Component {
        constructor(props){
        super(props)
        ...
        }
    componentDidMount() {
//TypeError: Cannot read property 'focus' of undefined
        if (this.props._ref && !this.props._ref.disabled) {
            this.props._ref.current.focus();
            this.props._ref.current.select();
        }
     }
        render(){

        //If I console.log of this.props._ref . 
        //I got function like function (input) { return this2.firstField  = input  }
        //If i try to do any focus () or select() method I got an error with msg 
        // Focus or select method is not a function 

        return(
        <div>
        <input  type="text" ref={this.props._ref} value = {this.props.value}  />
        </div>
        )
        }

自己的组件

class own extends React {
constructor(props){
super(props);
}

handleChange = () => {
//I need to check the cursor . where its reside if the cursor in first input field I need to disable the button like I have requirement . 
}

render(){

return(
<A value = {"userName"} _ref = {input => this.firstField = input }/>
)

}
}

正如我提到的我的场景,我不知道如何做到这一点。我希望 handleChange 方法可行吗? .请指导我。

如 ReactJs 文档中所述:

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

尝试使用 this.props._ref.current.focus()