ref未定义,尝试使用createRef获取输入ID

时间:2018-08-13 03:39:15

标签: javascript reactjs ecmascript-6

下面的代码有什么问题?我在id

上未定义
export default class ComponentName extends Component {
  myInput = React.createRef()

  handleChange = (event, inputRef) => {
    console.log('id', inputRef.id) //undefined
  }

  render() {
    return (
      <div>
        <input
          ref={this.myInput}
          id={this.props.id}
        />
        {children && (
          <label
            onClick={e => this.handleChange(e, this.myInput)}
            htmlFor={''}
          >
            {children}
          </label>
        )}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

应为console.log('id', this.inputRef.current.id)。为了安全起见

对DOM元素的实际引用实际上存在于ref对象的current属性中。

仔细研究docs中的示例时,我们看到.current属性引用了该元素

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

为方便起见,在此处输入示例

class CustomTextInput extends React.Component {   constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);   }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();   }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );   } }