Javascript 将参照与条件渲染一起使用
我对ref和条件渲染有问题。 我想在单击按钮标记时聚焦输入标记。 基本上,我有这个简化的代码Javascript 将参照与条件渲染一起使用,javascript,reactjs,reference,Javascript,Reactjs,Reference,我对ref和条件渲染有问题。 我想在单击按钮标记时聚焦输入标记。 基本上,我有这个简化的代码 class App extends React.Component { textInput constructor(props) { super(props) this.state = {isEditing: false} this.textInput = React.createRef() } onClick = () => { th
class App extends React.Component {
textInput
constructor(props) {
super(props)
this.state = {isEditing: false}
this.textInput = React.createRef()
}
onClick = () => {
this.setState({isEditing: !this.state.isEditing})
this.textInput.current.focus();
}
render () {
let edit = this.state.isEditing ?
(<input type="text" ref={this.textInput} />)
: ""
return (
<div>
<button onClick={this.onClick}>lorem </button>
{edit}
</div>
);
}
}
类应用程序扩展了React.Component{
文本输入
建造师(道具){
超级(道具)
this.state={isEditing:false}
this.textInput=React.createRef()
}
onClick=()=>{
this.setState({isEditing:!this.state.isEditing})
this.textInput.current.focus();
}
渲染(){
让编辑=this.state.isEditing?
()
: ""
返回(
洛勒姆
{编辑}
);
}
}
单击按钮时,将显示输入标记,但reftextInput
仍设置为null
。因此,我无法集中输入
我找到了一些解决方法,如:
- 在输入标记中设置
属性autoFocus
- 当isEditing==false时,使用css隐藏输入标记
this.setState({isEditing: !this.state.isEditing})
this.textInput.current.focus();
为此:
this.setState(previousState => ({isEditing: !previousState.isEditing}), () => {
this.textInput.current.focus();
});
更新:功能组件/挂钩 评论中询问了如何使用
useState
和功能组件来实现这一点。解释它,但我想提供更多的解释和一个可运行的示例
您仍然不希望在设置状态后立即读取它,但需要在状态更新和组件重新呈现后运行一些代码,而不是使用第二个参数回调到setState
。我们怎么做
答案是useffect
。效果的目的是将外部“事物”(例如:焦点之类的事物)与反应状态同步:
功能应用程序(道具){
const[isEditing,setIsEditing]=React.useState(false);
const textInputRef=React.useRef(null);
const-toggleEditing=()=>setiseediting(val=>!val);
//每当isEditing设置为true时,聚焦文本框
React.useffect(()=>{
如果(i编辑){
textInputRef.current.focus();
}
},[IsEdit,textInputRef]);
返回(
洛勒姆
{isEditing&&}
);
}
ReactDOM.render(
,
document.getElementById('root'))
);
非常感谢您的回答@rossipedia。我想知道我是否能用钩子做
显然,您不能像在setState中那样将第二个参数传递给useState setter。但是您可以像这样使用useEffect(注意useEffect中的第二个参数):
它成功了!;)
来源:添加了更多的细节,我知道了,我不知道我们可以将函数作为setState
的参数传递。是的,不幸的是,大多数文档通常不是以这种方式介绍setState
。在我看来,API应该只支持两个函数的形式,并且可能应该调用setStateAsync
,但不幸的是,这样做有点晚了:(@rossipedia,虽然您的方法仍然很好,但我建议使用functionalsetState()
在这里,因为新的状态取决于前一个状态。这也是官方文档推荐的方法。嘿,干得好,如何使用useState获得这个?
const [isEditing, setIsEditing] = React.useState(false);
React.useEffect(() => {
if (isEditing) {
textInput.current.focus();
}
}, [isEditing]);
const handleClick = () => setIsEditing(isEditing);