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