如何在 TextField 中使用 ref

GG-*_*sof 11 ref textfield material-ui

我原来的代码是这样的:

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>
);}
Run Code Online (Sandbox Code Playgroud)

name并且description可以正确获取输入。但是当我使用<TextField>

<TextField ref='name' placeholder='Enter the name of the item' />
Run Code Online (Sandbox Code Playgroud)

它显示传递的值是null,似乎ref不起作用。谁能帮我解决这个问题?

jag*_*ler 28

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

同样要获得<input />元素的引用,您应该使用inputRef道具。在这里阅读

如果你的 React 是最新的,你应该使用createRefuseRef钩子。下面是一些例子

// 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>
  );
}
Run Code Online (Sandbox Code Playgroud)
// 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢 - 只需将“ref”替换为“inputRef”就可以了。 (3认同)