javascript - 如何让 inputRef 从 <Textfield> 返回 &lt;input&gt; 元素?尝试了我能想到的一切,它仍然是空的

标签 javascript reactjs material-ui

我有一个 TextField,仅在单击另一个单选按钮时才呈现。根据 React 和 Material-UI 文档,我应该能够使用 TextField 上的 inputRef={this.myRef} 获取 Mui TextField 内输入元素的引用。我可以对另一个未切换的 TextField 执行此操作,但是当我尝试使用刚刚打开的 TextField 时,它显示为 null。

我尝试使用 inputRef={this.otherText} 和 inputProps={{ref: this.otherText}} 并得到相同的结果。

// Start of my class where I do the createRef()
class Form extends Component {
  constructor(props) {
    super(props);
    this.otherText = React.createRef();
  }

// Start of function where I try to reference the ref:
processApplication = e => {
    if (e.target.value.toLowerCase() === 'other') { // this triggers the         TextField to be rendered
        console.log(this.otherText); // Returns null, kinda - see screenshot
    }

// The TextField I'm trying to reference:
<TextField
    id='applicationOther'
    name='applicationOther'
    label='Describe application:'
    margin='normal'
    multiline={true}
    fullWidth={true}
    onChange={this.anyChange}
    autoFocus={true}
    inputRef={this.otherText}  // Here's where the reference is made
/>

我希望 this.otherText 有对该元素的引用,但 this.otherText.current 为 null。

最佳答案

因此,要将一些内容添加到任何提示(包括 Material TextField)的输入中,您可以将其指定为,例如:

this.state = { input: 'Some string' }
<TextField value={this.state.input} />

请记住不受控组件和受控组件之间的细微差别,因此根据您的用例,您可能需要传递 defaultValue 而不是 value。来自文档:

In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.

Docs link

关于javascript - 如何让 inputRef 从 <Textfield> 返回 &lt;input&gt; 元素?尝试了我能想到的一切,它仍然是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54372507/

相关文章:

javascript - 如何通过 jQuery AJAX 更新值

php - 如何将服务器数据传递给 React 组件

reactjs - React + Firebase - 删除映射组件内的 firebase 对象

html - Chrome 自动填充会导致文本字段标签和值的文本框发生冲突

javascript - 如何更改 Material ui TextField 的标签大小?

javascript - Heroku 上的 Angular 应用程序部署问题

javascript - 从 asp.net 中的 Web 服务绑定(bind)失败

javascript - 函数调用在回调中不起作用

javascript - 为 api 调用创建包装函数时遇到问题

css - 如何在 Material ui 对话框组件上添加背景图像