Reactjs 关注条件渲染组件中的输入文本
我在Reactjs 关注条件渲染组件中的输入文本,reactjs,Reactjs,我在reactJs中有条件渲染组件。我使用最新版本,并在我的应用程序中使用MaterialUi。此组件用于显示带有文本的跨距,一旦用户单击它,它将变为带有MaterialUi组件的输入,用户可以通过此组件更改字段 import React from 'react'; import EditIcon from '@material-ui/icons/Edit'; import TextField from '@material-ui/core/TextField'; import { grey40
reactJs
中有条件渲染组件。我使用最新版本,并在我的应用程序中使用MaterialUi
。此组件用于显示带有文本的跨距,一旦用户单击它,它将变为带有MaterialUi
组件的输入,用户可以通过此组件更改字段
import React from 'react';
import EditIcon from '@material-ui/icons/Edit';
import TextField from '@material-ui/core/TextField';
import { grey400 } from 'material-ui/styles/colors';
class InlineEditInput extends React.Component {
constructor(props) {
super(props);
this.state = {
hover: false,
edit: false,
value: this.props.children
};
this.textInput = React.createRef();
}
handleClick = event => {
event.stopPropagation();
if (!this.state.edit) {
this.setState({ value: this.props.children });
this.setState({ edit: true, hover: false });
}
};
handleBlur = () => {
this.setState({ edit: false });
if (this.state.value.length > 0 && this.state.value !== this.props.children) this.props.onChange(this.state.value);
else this.setState({ value: this.props.children });
};
handleMouseEnter = () => this.setState({ hover: true });
handleMouseLeave = () => this.setState({ hover: false });
render() {
let { hover, edit, value } = this.state;
const originalValue = this.props.children;
const styles = {
label: { minHeight: '2em', marginTop: '10px' },
editIcon: { width: 20, height: 20, fill: grey400, marginLeft: 8 },
editIconHidden: { width: 20, height: 20, fill: 'none', marginLeft: 8 }
};
const setFocus = () => {
this.textInput.focus();
};
if (!edit)
return (
<div onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<span onClick={this.handleClick}>{originalValue}</span>
{hover ? <EditIcon style={styles.editIcon} /> : <EditIcon style={styles.editIconHidden} />}
</div>
);
else
return (
<TextField
id="EditField"
ref={input => {
this.textInput = input;
setFocus();
}}
value={value}
onClick={this.handleClick}
onBlur={this.handleBlur}
onChange={event => this.setState({ value:event.target.value })}
/>
);
}
}
export default InlineEditInput;
如何编写此组件?尝试使用生命周期挂钩
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.state.edit)
this.textInput.focus();
}
您的方法没有获得聚焦的输入的原因可能是,当您实际创建ref时,DOM尚未插入。更像是创建了textInput元素,但它没有附加到DOM。只是直觉,不是100%确定
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.state.edit)
this.textInput.focus();
}