我正在尝试 focus()
React 中有条件渲染的文本区域。下面的代码与 React docs 中的示例几乎完全相同。或到 this similar question .
下面的代码立即显示并聚焦文本区域。如果三个注释行未被注释,文本区域将显示在 condition
之后 Prop 设置为 true
(其值取决于父级的状态,最初为 false
),但该元素不再获得焦点。
如果条件最初是true
,当组件第一次呈现时,输入元素会按预期获得焦点。当条件从 false
更改时会出现问题至 true
.
import React, { Component } from 'react'
class TestClass extends Component {
constructor(props) {
super(props)
this.focus = this.focus.bind(this)
}
componentDidMount() {
// this.props.condition &&
this.focus()
}
componentDidUpdate() {
// this.props.condition &&
this.focus()
}
focus() {
console.log(`this.textInput: ${this.textInput}`)
this.textInput.focus()
}
render() {
return (
<div>
{
// this.props.condition &&
<textarea
ref={(input) => {this.textInput = input}}
defaultValue="Thanks in advance for your invaluable advice">
{console.log('textarea rendered')}
</textarea>
}
</div>
)
}
}
控制台输出
textarea rendered
this.textInput: [object HTMLTextAreaElement]
排除该元素在时间focus()
不可用被执行。
此外:
- 设置
autoFocus
与 this question 相比,属性似乎不起作用 - 两个问题相同
<input />
和<textarea />
编辑:针对下面的问题,父组件如下所示。
class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
condition: false
}
this.toggleCondition = this.toggleCondition.bind(this)
}
toggleCondition() {
this.setState(prevState => ({
condition: !prevState.condition
}))
}
render() {
return (
<div>
<TestClass condition={this.state.condition} />
<button onMouseDown={this.toggleCondition} />
</div>
)
}
}
最佳答案
import React, { Component } from 'react';
class TestClass extends Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
componentDidMount() {
this.focus();
}
componentWillReceiveProps(nextProps) {
if (nextProps.condition !== this.props.condition) {
this.focus();
}
}
focus() {
console.log(`this.textInput: ${this.textInput}`);
if (this.props.condition === true) {
this.textInput.focus();
}
}
render() {
return (
<div>
{
this.props.condition &&
<textarea
ref={(input) => { this.textInput = input; }}
defaultValue="Thanks in advance for your invaluable advice"
>
{console.log('textarea rendered')}
</textarea>
}
</div>
);
}
}
export default TestClass;
关于javascript - React 不关注有条件呈现的输入/文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45276426/