あなたは、次の行を取り除くために必要な部分コード: onBlur={() => { this.setState({ openItems: false }) }}
それは基本的に言って、そのボタンを包むあなたのdivがフォーカスを失ったときに(たとえば、チェックボックスをクリックしたとき) state.openItems
変数をfalse
に設定し、ドロップダウンを閉じます。
編集: ここでの作業例は、https://codesandbox.io/s/jnq2rqwr53です。
ぼかしの代わりにonClick
を基本的に使用して、ドキュメントにclickイベントを追加すると、ユーザーはいつでもドキュメントの任意の場所をクリックしてhide
メソッドを呼び出し、モーダルを閉じます。選択したチェックボックスがチェックされますが、選択後に開いたままにしたい場合は、チェックボックスをオンにしても何も実行しないようにする必要があります(hide
)。 hide
メソッドの初めに、IDと簡単な条件ガードを使用して行いました。
コードは次のようになります。
Hello.js
import React, { Component } from 'react';
import classnames from 'classnames'
export default class CustomDropdown extends Component {
constructor() {
super()
this.state = {
openItems: false,
selectedItem: 'Please select'
}
this.show = this.show.bind(this);
this.hide = this.hide.bind(this);
}
show() {
this.setState({openItems: true});
document.addEventListener("click", this.hide);
}
hide(e) {
if (e.target.id === "1" || e.target.id === "2") {
return false;
}
this.setState({openItems: false});
document.removeEventListener("click", this.hide);
}
render() {
const { className, onOpen, children } = this.props
const { openItems, selectedItem } = this.state
return (
<div className={classnames('customDropdown', className)}>
<div tabIndex="1">
<button className="btn" onClick={this.show}>
{selectedItem}
</button>
<div className={classnames('items', { 'show': openItems === true, 'hide': openItems === false })}>
{children && children}
</div>
</div>
</div>
)
}
}
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './styles.css';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center'
};
class App extends Component {
constructor() {
super()
}
changeCheckbox =() => {
console.log('something')
}
render(){
return(
<div style={ styles }>
<Hello>
<div>
my checkbox 1
<input type="checkbox" onChange={this.changeCheckbox} id="1" />
</div>
<div>
my checkbox 2
<input type="checkbox" onChange={this.changeCheckbox} id="2" />
</div>
</Hello>
</div>
)
}
}
render(<App />, document.getElementById('root'));
デバッグヘルプ(「**なぜこのコードではありませんを求めている質問?** ")は、必要な動作、_特定の問題またはエラー_、およびそれを再現するのに必要な最短コードを含む必要があります** n自体**。 **明確な問題文**のない質問は他の読者には役に立たない。参照:[最小限で完全で検証可能なサンプルの作成方法](https://stackoverflow.com/help/mcve/)。 – Andreas
@Andreas私は例を挙げましたが、リンクを開いてselectをクリックしてから、チェックボックスをクリックしてみてください。 –
**質問そのもの** ...煙のように消えてしまうリンクは質問自体ではありません** - リンクが古くなったら今後の読者のことを考えてください –