如何在TextField中使用ref

49

我的原始代码是这样的:

handleClick() {
  var name = this.refs.name.value;
  var description = this.refs.description.value
}
render () {
return (
  <React.Fragment>
    <input ref='name' placeholder='Enter the name of the item' />
    <input ref='description' placeholder='Enter a description' />
    <Button onClick={this.handleClick.bind(this)}>Submit</Button>
  </React.Fragment>
);}

namedescription可以正确获取输入。 但是当我使用<TextField>时:

<TextField ref='name' placeholder='Enter the name of the item' />

它表明传递的值为null,似乎ref不起作用。 有人能帮我解决这个问题吗?


这回答了您的问题吗?如何在React的Material-UI中获取密码字段的值 - minus.273
2个回答

104

字符串引用已被弃用,并且 material-ui 不支持使用它们。 我建议阅读:https://reactjs.org/docs/refs-and-the-dom.html

此外,要获取对 <input />元素的引用,应使用 inputRef 属性。在此处阅读有关它的更多信息

如果您的 React 已经是最新版本,则应使用 createRef或useRef钩子。以下是一些示例:

<code><code>// Using the useRef() hook. Only possible when you're using a function component.
const App = () => {
  const textRef = useRef();
  const showRefContent = () => {
    console.log(textRef.current.value);
  };
  return (
    <div className="App">
      <TextField inputRef={textRef} />
      <button onClick={showRefContent}>Click</button>
    </div>
  );
}
</code></code>
<code><code>// Using createRef(). Use this when working in a React.Component
class App extends React.Component {
  constructor(props) {
    super(props);
    this.textRef = createRef();
  }

  showRefContent = () => {
    console.log(this.textRef.current.value);
  };

  render() {
    return (
      <div className="App">
        <TextField inputRef={this.textRef} />
        <button onClick={this.showRefContent}>Click</button>
      </div>
    );
  }
}
</code></code>

或者,如果您的React版本不是最新的,您可以将其存储在本地变量中,但这并不是首选方式。

<code><code>class App extends React.Component {
  showRefContent = () => {
    console.log(this.textRef.value);
  };

  render() {
    return (
      <div className="App">
        <TextField inputRef={element => (this.textRef = element)} />
        <button onClick={this.showRefContent}>Click</button>
      </div>
    );
  }
}
</code></code>

此外,您可能需要考虑使用状态(state)而不是必须为所有字段创建引用(refs),然后从DOM中检索值。


3
谢谢 - 只需将“ref”替换为“inputRef”,问题就解决了。 - Peter

3
当您使用“文本字段”时,应该使用“inputRef”属性而不是普通的“ref”属性。因为 MUI 文本字段组件由一些嵌套的普通 HTML 元素组成,使用“ref”属性无法访问任何特定的输入值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接