Javascript 太晚了
我正在尝试使文本框自动对焦 然而,我觉得调用Javascript 太晚了,javascript,reactjs,Javascript,Reactjs,我正在尝试使文本框自动对焦 然而,我觉得调用setState似乎太晚了 正在弹出窗口中调用它。显示。我创建了一个console.log按钮来记录状态,它似乎被设置为true,但它必须发生得太晚 如何将setState作为弹出窗口调用。show发生 class Dashboard extends React.Component { constructor(props) { super(props); this.state = { focused: false,
setState
似乎太晚了
正在弹出窗口中调用它。显示。我创建了一个console.log按钮来记录状态,它似乎被设置为true
,但它必须发生得太晚
如何将setState作为弹出窗口调用。show发生
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
focused: false,
};
}
onClick = (event) => {
console.log('Says focussed FALSE', this.state.focused)
this.setState({ focused:true });
Popup.show(<div>
<SearchBar
autoFocus
focused={this.state.focused}
/>
<button onClick={this.checkState}>It says TRUE here</button>
</div>,
console.log('Says focussed FALSE still', this.state.focused),
{ animationType: 'slide-up'});
};
checkState = (e) =>{
console.log(this.state)
}
render() {
return (
<div style={{ padding: '0.15rem' }}>
<Button onClick={this.onClick.bind(this)}>Open & Focus</Button>
</div>);
}
}
类仪表板扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
重点:错,
};
}
onClick=(事件)=>{
console.log('Says focused FALSE',this.state.focused)
this.setState({focused:true});
弹出显示(
这里说的是真的
,
console.log('表示聚焦假静止',this.state.focused),
{animationType:'向上滑动'});
};
检查状态=(e)=>{
console.log(this.state)
}
render(){
返回(
开放与聚焦
);
}
}
设置状态
不立即设置状态
发件人:
将setState()视为更新组件的请求,而不是即时命令。为了更好地感知性能,React可能会延迟它,然后在一次过程中更新多个组件。React不保证立即应用状态更改
将设置状态更改为类似
this.setState({ focused: true }, () => {
Popup.show(<div>
<SearchBar
autoFocus
focused={this.state.focused}
/>
<button onClick={this.checkState}>It says TRUE here</button>
</div>)
});
this.setState({focused:true},()=>{
弹出显示(
这里说的是真的
)
});
设置状态
不立即设置状态
发件人:
将setState()视为更新组件的请求,而不是即时命令。为了更好地感知性能,React可能会延迟它,然后在一次过程中更新多个组件。React不保证立即应用状态更改
将设置状态更改为类似
this.setState({ focused: true }, () => {
Popup.show(<div>
<SearchBar
autoFocus
focused={this.state.focused}
/>
<button onClick={this.checkState}>It says TRUE here</button>
</div>)
});
this.setState({focused:true},()=>{
弹出显示(
这里说的是真的
)
});
请始终记住,setState
不会立即执行。如果要在setState
之后使用Popup.show()
,可以使用回调:
this.setState({ focused: true }, () => {
Popup.show(...)
})
如果您已经在使用箭头函数,则不需要在渲染函数中使用.bind(this)
。请记住设置状态
不会立即执行。如果要在setState
之后使用Popup.show()
,可以使用回调:
this.setState({ focused: true }, () => {
Popup.show(...)
})
而且您已经在使用箭头函数,您不需要在渲染函数中使用.bind(this)
。可能重复的可能重复我认为这已经起作用,我的focused={this.state.focused}
仍然没有反应。有什么原因会这样吗?如果您将其更改为:this.setState({focused:true},()=>console.log(this.state.focused))代码>控制台中是否显示为true?如果是这样的话,问题可能就在你的搜索范围内。我想这已经奏效了,我的focused={this.state.focused}
仍然没有反应。有什么原因会这样吗?如果您将其更改为:this.setState({focused:true},()=>console.log(this.state.focused))代码>控制台中是否显示为true?如果是这样的话,问题可能就在你的搜索范围内。这似乎奏效了——但它仍然没有集中注意力。还有其他方法可以测试吗?这可能与弹出窗口
和搜索栏
有关,这似乎起了作用-但它仍然没有聚焦。还有其他方法可以测试吗?这可能与弹出窗口
和搜索栏