DraftJs内容简短说明

时间:2019-04-14 17:17:27

标签: reactjs draftjs draft-js-plugins

我有一个React应用程序并使用DraftJs。

在列表页面上,我的ContentCard组件使用草稿js中的编辑器将DraftJs内容呈现为只读。

 <Editor readOnly={true} editorState={contentState} /> 

我想显示contentState的简短版本作为简短描述,列表页面最多400个字符。并在内容详细信息页面上显示完整的contentState。

文档或简短说明插件中没有任何信息。

编辑ContentState并采用例如前两个代码块是真的方法吗?

1 个答案:

答案 0 :(得分:1)

我需要类似的东西,所以我做了一个非常粗糙的实现,但这对我有用:)

import { ContentState, convertToRaw } from 'draft-js'

const convertContentToEditorState = (content: string) => {
    if (content) {
        try {
            return EditorState.createWithContent(
                convertFromRaw(JSON.parse(content)),
            )
        } catch {
            return EditorState.createEmpty()
        }
    } else {
        return EditorState.createEmpty()
    }
}

/**
 * Takes in a stringfied JSON object, truncates it into a single ContentState and returns it.
 * @param jsonContentBlocks
 * @param maxCharCount
 */
const getTruncatedContentState = (
    jsonContentBlocks: string,
    maxCharCount: number,
): ContentState | undefined => {
    const editorState = convertContentToEditorState(jsonContentBlocks)

    const contentState = editorState.getCurrentContent()
    const blocks = contentState.getBlocksAsArray()

    let currentLength = 0
    const truncatedBlocks = []

    for (let i = 0; i < blocks.length; i++) {
        const blockLength = blocks[i].getCharacterList().size
        let truncatedText = ''

        if (blockLength >= maxCharCount - currentLength) {
            // We need to trim it
            truncatedText = blocks[i]
                .getText()
                .slice(0, maxCharCount - currentLength)
            currentLength += truncatedText.length

            const state = ContentState.createFromText(`${truncatedText}...`)
            truncatedBlocks.push(state.getFirstBlock())
            break
        } else if (blockLength > 0) {
            truncatedText = blocks[i].getText()
            currentLength += truncatedText.length

            const state = ContentState.createFromText(`${truncatedText}`)
            truncatedBlocks.push(state.getFirstBlock())
        }
    }

    if (truncatedBlocks.length > 0) {
        return ContentState.createFromBlockArray(truncatedBlocks)
    }

    return undefined
}

/**
 * Truncates and gets only the text from the blocks, returns stringified JSON
 * @param jsonContentBlocks
 * @param maxCharCount
 */
const getTruncatedContent = (
    jsonContentBlocks: string | undefined,
    maxCharCount: number,
): string | undefined => {
    if (!jsonContentBlocks) return undefined

    const contentState = getTruncatedContentState(
        jsonContentBlocks,
        maxCharCount,
    )

    if (contentState) {
        const raw = convertToRaw(contentState)
        return JSON.stringify(raw)
    }

    return undefined
}