[英]How do I get inputRef to return <input> element from <Textfield>? Tried everything I can think of and it's still null
我有一个仅在单击另一个单选按钮时呈现的 TextField。 根据 React 和 Material-UI 文档,我应该能够使用 TextField 上的 inputRef={this.myRef} 获取对 Mui TextField 内输入元素的引用。 我可以为另一个未切换的 TextField 执行此操作,但是当我尝试使用刚刚打开的 TextField 时,它显示为空。
我试过使用 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 为空。
因此,要将一些内容添加到任何类型的输入中,包括 Material TextField
,您可以将其分配为value
,例如:
this.state = { input: 'Some string' }
<TextField value={this.state.input} />
请记住不受控制和受控组件之间的细微差别,因此根据您的用例,您可能希望传递defaultValue
而不是value
。 从文档:
在 React 渲染生命周期中,表单元素上的 value 属性将覆盖 DOM 中的值。 对于不受控制的组件,您通常希望 React 指定初始值,但不控制后续更新。 要处理这种情况,您可以指定
defaultValue
属性而不是value
。
我有同样的问题,做以下工作对我有用:
<TextField
variant="filled"
inputRef={(input) => {
if(input != null) {
input.focus();
}
}}
/>
在我的情况下,这里的技巧是if(input != null)
。 您还可以在此处查看工作示例: CodeSandBox- Material-ui-TextFieldFocus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.