java 如何返回输入焦点,渲染后将焦点设置在输入上

我刚刚遇到了这个问题而且我正在使用react 15.0.1 15.0.2而且我从其他答案中得到了我需要的东西,因为自从v.15在几周之前掉了一些this.refs properties were deprecated和removed .

一般来说,我需要的是:

在组件安装时,聚焦第一个输入(字段)元素

将第一个输入(字段)元素聚焦并显示错误(提交后)

我正在使用:

React容器/演示组件

Redux

React-Router

聚焦第一个输入元素

我在页面的第一个 上使用 autoFocus={true} ,这样当组件安装时,它将获得焦点 .

使用错误聚焦第一个输入元素

这花费的时间更长,更复杂 . 为了简洁,我保留了与解决方案无关的代码 .

Redux商店/州

我需要一个全局状态来知道我是否应该设置焦点并在设置时禁用它,所以我不会't keep re-setting focus when the components re-render (I'将使用 componentDidUpdate() 来检查设置焦点 . )

这可以按照您认为适合您的应用程序进行设计 .

{

form: {

resetFocus: false,

}

}

容器组件

组件需要设置 resetfocus 属性,并且如果最终将焦点设置为自身,则需要使用callBack清除属性 .

还要注意,我将Action Creators组织成单独的文件,主要是因为我的项目相当大,我想将它们分解成更易于管理的块 .

import { connect } from 'react-redux';

import MyField from '../presentation/MyField';

import ActionCreator from '../actions/action-creators';

function mapStateToProps(state) {

return {

resetFocus: state.form.resetFocus

}

}

function mapDispatchToProps(dispatch) {

return {

clearResetFocus() {

dispatch(ActionCreator.clearResetFocus());

}

}

}

export default connect(mapStateToProps, mapDispatchToProps)(MyField);

演示组件

import React, { PropTypes } form 'react';

export default class MyField extends React.Component {

// don't forget to .bind(this)

constructor(props) {

super(props);

this._handleRef = this._handleRef.bind(this);

}

// This is not called on the initial render so

// this._input will be set before this get called

componentDidUpdate() {

if(!this.props.resetFocus) {

return false;

}

if(this.shouldfocus()) {

this._input.focus();

this.props.clearResetFocus();

}

}

// When the component mounts, it will save a

// reference to itself as _input, which we'll

// be able to call in subsequent componentDidUpdate()

// calls if we need to set focus.

_handleRef(c) {

this._input = c;

}

// Whatever logic you need to determine if this

// component should get focus

shouldFocus() {

// ...

}

// pass the _handleRef callback so we can access

// a reference of this element in other component methods

render() {

return (

);

}

}

Myfield.propTypes = {

clearResetFocus: PropTypes.func,

resetFocus: PropTypes.bool

}

概述

一般的想法是,每个可能有错误并被集中的表单字段需要检查自己以及是否需要将注意力集中在自身上 .

需要发生业务逻辑以确定给定字段是否是设置焦点的正确字段 . 这没有显示,因为它取决于个人应用 .

提交表单时,该事件需要将全局焦点标志 resetFocus 设置为true . 然后每个组件更新本身,它将看到它应该检查它是否得到焦点,如果它,它调度事件重置焦点,以便其他元素不必继续检查 .

编辑作为旁注,我在"utilities"文件中有我的业务逻辑,我只是导出了方法并在每个 shouldfocus() 方法中调用它 .

干杯!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值