React refs没有为输入字段提供正确的输出

问题描述 投票:0回答:2

React ref没有给出正确的输出。它返回'refr <input type =“text”placeholder =“ssssssssss”>'而不是包含焦点等函数的ref对象。

请检查以下代码 -

render() {
    return (
      <div>
        <input 
          type="text" 
          ref={(refr) => console.log('refr', refr)} 
          placeholder='ssssssssss'/>
      </div>
    )
}

所以在控制台中,它将日志打印为'refr <input type =“text”placeholder =“ssssssssss”>'。这有什么问题吗?

reactjs
2个回答
0
投票

ref属性返回对ref所在元素或组件的引用。

试试这段代码:

render() {
    return (
      <div>
        <input 
          type="text" 
          ref={function(param) {console.log(param)}}
          placeholder='ssssssssss'/>
      </div>
    )
}

有关更多详细信息,请阅读本文https://www.reactenlightenment.com/basic-react-components/6.9.html


-1
投票

这是使用refs作为输入元素的示例

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in an instance field (for example, this.textInput).
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

参考link

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