私は2つのコンポーネントを持っています。コンポーネントAで誰かがボタンをクリックすると、入力フィールドをコンポーネントBに集中させたい。React/Redux: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
に入っているので、私はこのコンポーネントに間違ったことがあると思います。アクション。
これは働いた!ありがとうございました! –