我有两个组成部分。当在组件A中有人点击一个按钮时,我想要将输入字段集中在组件B中。反应,和/终极版:专注于componentWillReceiveProps输入字段不工作
我使用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
条件,我认为有什么不对的组成部分,不是我的减速/终极版或含有按钮,调度其他组件那个行动。
这工作!谢谢! –