简体   繁体   中英

How to extract text without HTML Entities encoding from React ContentEditable?

I have this textArea based on react react-contenteditable. When a user writes something

for example "A & B", the e.target.value; in onChange event handler return it as "A & amp; B". How can I extract it the same as the original text?

onChange(e) {
    const val = e.target.value;

    this.setState({
        value: val
    });
    return this.props.onChange(e, this.props.value, val);
}

onPaste(e) {
    e.preventDefault();
    const text = e.clipboardData.getData("text/plain");

    document.execCommand("insertText", false, text);
    return true;
}

render() {
    return (
        <ContentEditable
            className={this.state.className}
            html={this.state.value}
            placeholder={this.props.placeholder}
            disabled={false}
            onPaste={this.onPaste}
            onBlur={::this.onBlur}
            onFocus={::this.onFocus}
            onChange={::this.onChange}
        />
    );
}

This package is meant to handle HTML (for rich text) thus the value returned is HTML. But if you want the parsed text (which will lack the rich text) you can directly read the text from the contenteditable div.

The package provides a nice interface to forward a ref to the contenteditable div with the prop innerRef . You can then access the parsed text any time with innerRef.current.innerText .

constructor() {
    this.editableRef = React.createRef(null);
}

onChange(e) {
    console.log(this.editableRef.current.innerText);

    const val = e.target.value;
    this.setState({ value: val });
    return this.props.onChange(e, this.props.value, val);
}


render() {
    return (
        <ContentEditable
            innerRef={this.editableRef}
            html={this.state.value}
            onChange={::this.onChange}
        />
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM