[英]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.