[英]React / Redux: focus input field in componentWillReceiveProps not working
我有两个组成部分。 当有人在组件A中单击按钮时,我想在组件B中集中一个输入字段。
我正在使用Redux,并且在我的Redux存储中保存了dataInputFocus
,并且每当将其设置为true时,我都会重新渲染组件并希望集中输入字段。 但是,这不起作用:调用componentWillReceiveProps(nextProps)
,它也进入if
(我尝试过一些console.logs
),但是this.myInp.focus();
只是不工作。
// Import React
import React from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {addData, setInputFocus} from '../actions/index'
// Create Search component class
class Data extends React.Component{
constructor(props) {
super(props);
this.state = { value: ""};
this.handleInputChange = this.handleInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
componentWillReceiveProps(nextProps){
if(nextProps.applicationState.dataInputFocus) {
this.myInp.focus();
}
}
onFormSubmit(e) {
e.preventDefault();
this.setState({value: "" });
this.props.addData(this.state.value, this.props.preferences.type);
}
handleInputChange(e) {
this.setState({value: e.target.value })
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
placeholder="data"
className="myInput"
value={this.state.value}
onChange={this.handleInputChange}
ref={(ip) => this.myInp = ip}
/>
<button>Add</button>
<span>{this.props.applicationState.dataInputFocus? 'TRUE' : 'FALSE'}</span>
{/* I added this line in order to test whether this actually works, but also so that my component re-renders, since I would not actually use dataInputFocus anywhere other than in the conditional */}
</form>
<button onClick={() => {this.myInp.focus()}}>Focus Input</button> {/* this however does(!) work */}
</div>
);
}
}
// Export Search
function mapStateToProps (state) {
return {
data: state.data,
preferences: state.preferences,
applicationState: state.applicationState
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
addData: addData
}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(Data);
这是接收道具并包含要聚焦的输入字段的组件。 因为它进入了componentWillReceiveProps
并且我也检查了道具实际上是否在变化,并且进入了if
条件,所以我认为这个组件有问题,而不是我的reducer / redux或其他包含按钮和调度的组件那个行动。
我有一个原因,该行( this.myInp.focus();
)无法正常工作,因为组件是在componentWillReceiveProps之后呈现的,并且无法找到ref={(ip) => this.myInp = ip}
引用输入框的内容...所以请在下面查看我的想法。
//create a state variable or global variable
var isFocus= false
constructor(props) {
super(props);
this.state = { value: "" };
this.handleInputChange = this.handleInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
// change value
componentWillReceiveProps(nextProps){
if(nextProps.applicationState.dataInputFocus) {
isFocus= true
}
}
//after getting reference from render function make it focus..
componentDidMount()
{
if(isFocus)
this.myInp.focus();
}
干杯:)
更新组件后 ,应使用componentDidUpdate对DOM进行操作,而不要使用componentWillReceiveProps(在重新渲染发生之前调用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.