gpt4 book ai didi

reactjs - 如何使用 Redux 和 ReactJS 等声明式/函数式样式库来处理焦点?

转载 作者:行者123 更新时间:2023-12-03 13:20:28 25 4
gpt4 key购买 nike

在查看其他开发人员在使用 Redux 时处理输入焦点的方式时,我发现了一些关于 ReactJS components such as this 的一般指南。然而,我担心 focus() 函数是必需的,并且我可能会看到多个组件争夺焦点时可能会出现奇怪的行为。有没有一种redux方式来处理焦点?是否有人使用 reduxreact 来务实地设置焦点?如果有,你会使用什么技术?

相关:

最佳答案

我的方法是使用 ref 回调,它是一种元素的 onRenderComplete 。在该回调中,我可以聚焦(有条件地,如果需要)并获得 future 聚焦的引用。

如果在操作运行后有条件地渲染输入,则该 ref 回调应触发焦点,因为在调用操作后,引用还不立即存在,而仅在渲染完成后才存在。处理诸如 focus 之类的 componentDidUpdate 看起来就像一团糟。

// Composer.jsx -- contains an input that will need to be focused somewhere else

class Composer extends Component {
render() {
return <input type="text" ref="input" />
}

// exposed as a public method
focus() {
this.refs.input.focus()
}
}

// App.jsx

@connect(
state => ({ isComposing: state.isComposing }),
...
)
class App extends Component {
render() {
const { isComposing } = this.props // or props, doesn't matter
return (
<div>
<button onClick={::this._onCompose}>Compose</button>
{isComposing ? <Composer ref={c => {
this._composer = c
this._composer && this._composer.focus() // issue initial focus
}} /> : null}
</div>
)
}

_onCompose() {
this.props.startComposing() // fire an action that changes state.isComposing

// the first time the action dispatches, this._composer is still null, so the ref takes care of the focus. After the render, the ref remains so it can be accessed:

this._composer && this._composer.focus() // focus if ref already exists
}
}

为什么不使用 autoFocusisFocued 属性?

由于 HTMLInputElementvalue 作为 prop,但将 focus() 作为方法 - 而不是 isFocused prop——我会继续使用方法来处理这个问题。 isFocused 可以获取一个值,但如果用户对输入模糊,该值会发生什么情况?就会不同步了另外,正如评论中提到的,autoFocus 可能与多个组件发生冲突

那么如何在 props 和 method 之间做出选择呢?

对于大多数情况, Prop 就是答案。方法只能用在“即发即忘”的情况下,例如聊天中收到新消息时的 scrollToBottomscrollIntoView 等。这些是商店不关心的一次性行为,用户可以通过交互进行更改,因此 bool 属性不适合。对于所有其他事情,我会使用 Prop 。

这是一个 jsbin:

http://jsbin.com/waholo/edit?html,js,output

关于reactjs - 如何使用 Redux 和 ReactJS 等声明式/函数式样式库来处理焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34841777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com