Blazor Server에서 사용하던
SearchBox 컴포넌트를 React.js 컴포넌트로 만들어 보았습니다.
SearchBox.jsx
import React, { Component } from 'react';
export class SearchBox extends Component {
constructor(props) {
super(props);
this.state = {
searchQuery: ""
};
this.debounce = this.debounce.bind(this);
this.searchQueryChanged = this.searchQueryChanged.bind(this);
this.sendSearchQuery = this.sendSearchQuery.bind(this);
}
sendSearchQuery() {
this.props.searchQueryChanged(this.state.searchQuery); // SearchQuery를 부모 컴포넌트로 전송
}
searchQueryChanged(e) {
const qry = e.target.value;
this.setState({ searchQuery: qry });
console.log(qry);
this.searchHandler();
}
searchHandler = this.debounce(() => {
console.log("Child", this.state.searchQuery);
this.sendSearchQuery();
}, 3000);
debounce(fn, interval) {
let debounceTimer
return _ => {
clearTimeout(debounceTimer)
debounceTimer = setTimeout(_ => {
debounceTimer = null
fn.apply(this, arguments)
}, interval)
};
}
render() {
return (
<>
<div className="input-group mb-3">
<input className="form-control form-control-sm form-control-borderless" type="search" placeholder="Search topics or keywords" aria-describedby="btnSearch"
value={this.state.searchQuery}
onChange={this.searchQueryChanged}
/>
<div className="input-group-append">
<button className="btn btn-sm btn-success" type="button" onClick={this.sendSearchQuery}>Search</button>
</div>
</div>
</>
);
}
}
SearchComponent.jsx
import React, { Component } from 'react';
import { SearchBox } from '../Shared/SearchBox';
export class SearchComponent extends Component {
constructor(props) {
super(props);
this.state = {
searchQuery: ''
};
this.searchQueryChanged = this.searchQueryChanged.bind(this);
}
searchQueryChanged(searchQuery) {
console.log("Parent", searchQuery);
this.setState({ searchQuery: searchQuery });
}
render() {
return (
<>
<h1>SearchBox Component Test</h1>
<SearchBox
searchQueryChanged={(searchQuery) => this.searchQueryChanged(searchQuery)}>
</SearchBox>
</>
);
}
}
참고로, 검색 박스에 대한 사용은
React.js 게시판 프로젝트 강좌에서 사용됩니다.
끝.