【发布时间】:2017-10-04 19:03:42
【问题描述】:
我有两个组件。当在组件 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或其他包含的组件按钮并调度操作。
【问题讨论】:
标签: javascript reactjs react-native redux react-redux