【问题标题】:How can I use ref in TextField如何在 TextField 中使用 ref
【发布时间】:2020-04-26 02:41:42
【问题描述】:

我原来的代码是这样的:

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 可以正确获取输入。 但是当我使用&lt;TextField&gt;:

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

显示传递的值为null,看来ref不起作用。 谁能帮我解决这个问题?

【问题讨论】:

标签: material-ui textfield ref


【解决方案1】:

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

还要获得&lt;input /&gt; 元素的引用,您应该使用inputRef 属性。 Read about it here.

如果你的 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>
  );
}
// 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>
    );
  }
}

或者,如果您的 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>
    );
  }
}

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

【讨论】:

  • 谢谢 - 只需将“ref”替换为“inputRef”就可以了。
猜你喜欢
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 2014-03-09
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2019-06-16
相关资源
最近更新 更多