如何在TextField中使用ref

如何在TextField中使用ref

本文介绍了如何在TextField中使用ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的原始代码是这样的:

my original code was like this:

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>
);}

名称 description 可以正确获取输入.但是当我使用< TextField> 时:

name and description can get the inputs correctly.But when I use <TextField>:

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

它表明传递的值为 null ,看来 ref 不起作用.谁能帮我解决这个问题?

it shows that the value passed is null, it seems that ref does not work.Can anyone help me solve this problem?

推荐答案

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

String refs are deprecated and material-ui does not support using them. I recommend reading: https://reactjs.org/docs/refs-and-the-dom.html

还要获取对< input/> 元素的引用,您还应该使用 inputRef 道具.在此处阅读.

Also to get a ref to the <input /> element you should use the inputRef prop. Read about it here.

如果您的React是最新版本,则应使用 useRef 钩子的 createRef .下面是一些例子

If your React is update to date you should use createRef of the useRef hook. Below are some examples

// 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不是最新的,则可以将其存储在本地变量中,但这不是首选方式.

Or if your React isn't up to date you can store it in a local variable, but this isn't the preferred way.

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中检索值.

Also, you might want to consider using state instead of having to create refs for all fields and then retrieving the values from the dom.

这篇关于如何在TextField中使用ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:55