文章源碼:https://github.com/Haixiang6123/my-react-contenteditable
以前在知乎看到一篇關於《一行代理可以做什麼?》的回答:
當時試了一下確實很好玩,於是每次都可以在妹子面前秀一波操作,在他們驚歎的目光中,我心裏開心地笑了——嗯,又讓一個不懂技術的人發現到了程序的美🐶,咳咳。
一直以來,我都覺得這個屬性只是爲了存在而存在的,然而在今天接到的需求之後,我發現這個感覺沒什麼用的屬性竟然完美地解決了我的需求。
一個需求
需求很簡單,在輸入框裏添加按鈕就好了。這種功能一般用於郵件羣發,這裏的按鈕“姓名”其實就是一個變量,後端應該要自動填充真實用戶的姓名,然後再把郵件發給用戶的。
這個需求第一感覺像是 textarea 里加入一個 button,但是想想又不對:textarea 里加不了 button。那用 div 包裹呢?也不對:div 不能輸入啊,唉,誰說不能輸入的?contentEditable
屬性就是可以讓用戶手動輸入的。
下面就帶大家手寫一個 react-contenteditable
的輪子吧。
用例
參考 input 元素的受控組件寫法,可以想到肯定得有 value
和 onChange
兩個 props,使用方法大概像這樣:
function App() {
const [value, setValue] = useState('');
const onChange = (e: ContentEditableEvent) => {
console.log('change', e.target.value)
setValue(e.target.value)
}
return (
<div style={{ border: '1px solid black' }}>
<ContentEditable style={{ height: 300 }} value={value} onChange={onChange} />
</div>
);
}
重新再認識一下 contentEditable
屬性:一個枚舉屬性,表示元素是否可被用戶編輯。瀏覽器會修改元素的部件以允許編輯。詳情可看 MDN 文檔。
爲了可以插入 html,需要用到 dangerouslySetInnerHTML
這個屬性來設置 innerHTML
,並通過 onInput
來執行 onChange
回調。一個簡單的實現如下:
// 修改後的 onChange 事件
export type ContentEditableEvent = SyntheticEvent<any, Event> & {
target: { value: string }
};
interface Props {
value?: string // 值
onChange?: (e: ContentEditableEvent) => void // 值改動的回調
}
class ContentEditable extends Component<Props> {
lastHtml = this.props.value // 記錄上一次的值
ref = createRef<HTMLDivElement>() // 當前容器
emitEvent = (originalEvent: SyntheticEvent<any>) => {
if (!this.ref.current) return
const html = this.ref.current.innerHTML
if (this.props.onChange && html !== this.lastHtml) { // 與上次的值不一樣纔回調
const event = { // 合併事件,這裏主要改變 target.value 的值
...originalEvent,
target: {
...originalEvent.target,
value: html || ''
}
}
this.props.onChange(event) // 執行回調
}
}
render() {
const { value } = this.props
return (
<div
ref={this.ref}
contentEditable
onInput={this.emitEvent}
dangerouslySetInnerHTML={{__html: value || ''}}
/>
)
}
}
但是很快你會發現一個問題:怎麼打出來的字都是倒着輸出的?比如打個 "hello",會變成:
解決倒序輸出的問題
如果你把 onChange
裏的 setValue(e.target.value)
去掉,會發現這個 bug 又沒了,又可以正常輸出了。
這是因爲每次 setValue
的時候組件會重新渲染,每次渲染的時候光標會跑到最前面,所以當 setValue
的時候會出現倒序輸出的問題。
解決方法是在 componentDidUpdate
裏把光標重新放到最後就可以了,每次渲染後光標回到最後的位置。
const replaceCaret = (el: HTMLElement) => {
// 創建光標
const cursor = document.createTextNode('')
el.appendChild(cursor)
// 判斷是否選中
const isFocused = document.activeElement === el
if (!cursor || !cursor.nodeValue || !isFocused) return
// 將光標放到最後
const selection = window.getSelection()
if (selection !== null) {
const range = document.createRange()
range.setStart(cursor, cursor.nodeValue.length)
range.collapse(true)
selection.removeAllRanges()
selection.addRange(range)
}
// 重新 focus
if (el instanceof HTMLElement) el.focus()
}
class ContentEditable extends Component<Props> {
lastHtml = this.props.value
ref = createRef<HTMLDivElement>()
componentDidUpdate() {
if (!this.ref.current) return
this.lastHtml = this.props.value
replaceCaret(this.ref.current) // 把光標放到最後
}
...
}
這裏要注意的是:對於 Range,可以是選區,也可以是光標。上面創建了一個 Range,setCollapse(true)
把 Range 設置爲 空選區 也就變成了光標的了。然後把 Range 放到創建的 Node 裏,這個 Node 又放到容器最後。這就實現了 “把光標放到最後” 的效果了。
checkUpdate
有人可能會有疑問:一般使用 input
之類輸入組件的時候,如果沒在 onChange
裏 setValue
,值都是不會改變的呀。上面提到不加 setValue
也可以再次輸入,也就說我設置 value
就好了,不用手動再去更新 value
了,這裏是不是可以做輸入性能的優化呢?
答案是可以的,在 react-contentedtiable 源碼 裏就做了性能的優化。
shouldComponentUpdate(nextProps: Props): boolean {
const { props } = this;
const el = this.getEl();
// We need not rerender if the change of props simply reflects the user's edits.
// Rerendering in this case would make the cursor/caret jump
// Rerender if there is no element yet... (somehow?)
if (!el) return true;
// ...or if html really changed... (programmatically, not by user edit)
if (
normalizeHtml(nextProps.html) !== normalizeHtml(el.innerHTML)
) {
return true;
}
// Handle additional properties
return props.disabled !== nextProps.disabled ||
props.tagName !== nextProps.tagName ||
props.className !== nextProps.className ||
props.innerRef !== nextProps.innerRef ||
!deepEqual(props.style, nextProps.style);
}
但是隨之而來的是由於阻止更新而引發的 Bug:https://github.com/lovasoa/react-contenteditable/issues/161。
在這個 Issue 裏說到因爲沒有對 onBlur
進行更新判斷,因此,每次改變了值之後,再觸發 blur 事件,值都不會改變。那加個 onBlur
的檢查是否可行呢?如果要這麼做,那別的 onInput
,onClick
等回調也要加判斷纔可以,其實這麼下來還不如在 shouldComponentUpdate
裏 return true
就好了。完全起不到性能優化的作用。
一個比較折中的方案是添加一個 checkUpdate
的 props 給使用的人去做性能優化。源碼是對每次的值以及一些 props
更新進行判定是否需要更新。
interface Props extends HTMLAttributes<HTMLElement> {
value?: string
onChange?: (e: ContentEditableEvent) => void
checkUpdate?: (nextProps: Props, thisProps: Props) => boolean // 判斷是否應該更新
}
在 shouldComponentUpdate
裏返回這個函數的返回值即可:
class ContentEditable extends Component<Props> {
...
shouldComponentUpdate(nextProps: Readonly<Props>): boolean {
if (this.props.checkUpdate) {
return this.props.checkUpdate(nextProps, this.props)
}
return true
}
...
}
innerRef
上面通過 ref 獲取容器元素的代碼比較冗餘,而且還沒有向外暴露 ref。這一步優化獲取容器元素代碼,並向外暴露 ref 參數。
interface Props extends HTMLAttributes<HTMLElement> {
disabled?: boolean
value?: string
onChange?: (e: ContentEditableEvent) => void
innerRef?: React.RefObject<HTMLDivElement> | Function // 向外暴露的 ref
checkUpdate?: (nextProps: Props, thisProps: Props) => boolean
}
需要注意的是,ref 可能爲 Ref 對象,也可能爲一個函數,要兼容這兩種情況。
class ContentEditable extends Component<Props> {
private lastHtml: string = this.props.value || ''
private el: HTMLElement | null = null
componentDidUpdate() {
const el = this.getEl()
if (!el) return
this.lastHtml = this.props.value || ''
replaceCaret(el)
}
getEl = (): HTMLElement | null => { // 獲取容器的方法
const {innerRef} = this.props
if (!!innerRef && typeof innerRef !== 'function') {
return innerRef.current
}
return this.el
}
emitEvent = (originalEvent: SyntheticEvent<any>) => {
const el = this.getEl()
if (!el) return
const html = el.innerHTML
if (this.props.onChange && html !== this.lastHtml) {
const event = {
...originalEvent,
target: {
value: html || ''
}
}
// @ts-ignore
this.props.onChange(event)
}
this.lastHtml = html
}
render() {
const { disabled, value, innerRef, ...passProps } = this.props
return (
<div
{...passProps}
ref={typeof innerRef === 'function' ? (node: HTMLDivElement) => {
innerRef(node)
this.el = node
}: innerRef || null}
contentEditable
onInput={this.emitEvent}
onBlur={this.props.onBlur || this.emitEvent}
onKeyUp={this.props.onKeyUp || this.emitEvent}
onKeyDown={this.props.onKeyDown || this.emitEvent}
dangerouslySetInnerHTML={{__html: value || ''}}
>
{this.props.children}
</div>
)
}
}
上面添加了 getEl
函數,用於獲取當前容器。
補充 props
除了上面一些比較重要的 props,還有一些增強擴展性的 props,如 disabled
, tagName
。
class ContentEditable extends Component<Props> {
...
render() {
const {tagName, value, innerRef, ...passProps} = this.props
return createElement(
tagName || 'div',
{
...passProps,
ref: typeof innerRef === 'function' ? (node: HTMLDivElement) => {
innerRef(node)
this.el = node
} : innerRef || null,
contentEditable: !this.props.disabled,
onInput: this.emitEvent,
onBlur: this.props.onBlur || this.emitEvent,
onKeyUp: this.props.onKeyUp || this.emitEvent,
onKeyDown: this.props.onKeyDown || this.emitEvent,
dangerouslySetInnerHTML: {__html: value || ''}
},
this.props.children
)
}
}
總結
至此,一個 react-contenteditable 的組件就完成了,主要實現了:
- value 和 onChange 的數據流
- 在
componentDidUpdate
裏處理光標總是被放在最前面的問題 - 在
shouldComponentUpdate
裏添加checkUpdate
,開發者用於優化渲染性能 - 向外暴露 ref,disabled,tagName 的 props
雖然這個 react-contenteditable 看起來還不錯,但是看了源碼之後發現這個庫的很多兼容性的問題都沒有考慮到,比如 這篇 Stackoverflow 上的討論,再加上上面提到的蛋疼 Issue,如果真要在生產環境實現富文本最好不要用這個庫,推薦使用 draft.js。當然簡單的功能用這個庫實現還是比較輕量的。