[javascript] Draft.js에서 텍스트 에디터의 글자 크기 변경 기능 추가하기
Draft.js는 React 기반의 강력한 텍스트 에디터 라이브러리입니다. 사용자가 텍스트를 입력하고 편집할 수있는 기능을 제공하며, 다양한 사용자 정의 기능을 추가할 수 있습니다.
이번에는 Draft.js 에디터에 글자 크기를 변경하는 기능을 추가하는 방법에 대해 알아보겠습니다.
1. 텍스트 스타일 설정
먼저, 텍스트 스타일을 설정하기 위해 InlineStyleButton 컴포넌트를 생성합니다. 이 컴포넌트는 사용자가 텍스트를 선택하고 글자 크기를 변경할 수 있도록 합니다.
import React from 'react';
import { EditorState, RichUtils } from 'draft-js';
class InlineStyleButton extends React.Component {
constructor(props) {
super(props);
this.toggleStyle = this.toggleStyle.bind(this);
}
toggleStyle() {
const { editorState, onChange, style } = this.props;
onChange(RichUtils.toggleInlineStyle(editorState, style));
}
render() {
const { active, label } = this.props;
return (
<button
className={active ? 'active' : ''}
onClick={this.toggleStyle}
>
{label}
</button>
);
}
}
export default InlineStyleButton;
2. 글자 크기 변경 기능 추가
다음으로, 글자 크기를 변경할 수 있는 버튼을 에디터 상단에 추가해야합니다.
import React from 'react';
import { Editor, EditorState } from 'draft-js';
import InlineStyleButton from './InlineStyleButton';
class TextEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
};
this.onChange = this.onChange.bind(this);
}
onChange(editorState) {
this.setState({ editorState });
}
render() {
const { editorState } = this.state;
return (
<div>
<div>
<InlineStyleButton
label="작게"
style="SMALL_SIZE"
editorState={editorState}
onChange={this.onChange}
active={
editorState.getCurrentInlineStyle().has('SMALL_SIZE')
}
/>
<InlineStyleButton
label="보통"
style="MEDIUM_SIZE"
editorState={editorState}
onChange={this.onChange}
active={
editorState.getCurrentInlineStyle().has('MEDIUM_SIZE')
}
/>
<InlineStyleButton
label="크게"
style="LARGE_SIZE"
editorState={editorState}
onChange={this.onChange}
active={
editorState.getCurrentInlineStyle().has('LARGE_SIZE')
}
/>
</div>
<Editor
editorState={editorState}
onChange={this.onChange}
/>
</div>
);
}
}
export default TextEditor;
위의 예제에서 사용된 “SMALL_SIZE”, “MEDIUM_SIZE”, “LARGE_SIZE”는 CSS 스타일을 적용할 클래스 이름입니다. 해당 클래스에 대한 스타일을 작성하여 텍스트의 크기를 제어할 수 있습니다.
이제 글자 크기 변경 기능이 있는 텍스트 에디터를 사용할 준비가 되었습니다.
결론
이 튜토리얼에서는 Draft.js 에디터에 글자 크기 변경 기능을 추가하는 방법을 소개했습니다. 이를 통해 사용자는 텍스트를 작게, 보통 크기, 또는 크게 조절하여 텍스트의 가독성을 개선할 수 있습니다.
더 많은 기능을 추가하려면 Draft.js 문서를 참조해보세요. https://draftjs.org/
참고 링크: