自适应高度文本框 react contenteditable
import React, { Component } from 'react';
import PropTypes from 'prop-types';
const reduceTargetKeys = (target, keys, predicate) => Object.keys(target).reduce(predicate, {});
const omit = (target = {}, keys = []) =>
reduceTargetKeys(target, keys, (acc, key) => keys.some(omitKey => omitKey === key) ? acc : { ...acc, [key]: target[key] });
const pick = (target = {}, keys = []) =>
reduceTargetKeys(target, keys, (acc, key) => keys.some(pickKey => pickKey === key) ? { ...acc, [key]: target[key] } : acc);
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const propTypes = {
content: PropTypes.string,
editable: PropTypes.bool,
focus: PropTypes.bool,
maxLength: PropTypes.number,
multiLine: PropTypes.bool,
sanitise: PropTypes.bool,
caretPosition: PropTypes.oneOf(['start', 'end']),
tagName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), // The element to make contenteditable. Takes an element string ('div', 'span', 'h1') or a styled component
innerRef: PropTypes.func,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
onKeyDown: PropTypes.func,
onPaste: PropTypes.func,
onChange: PropTypes.func,
styled: PropTypes.bool, // If element is a styled component (uses innerRef instead of ref)
};
const defaultProps = {
content: '',
editable: true,
focus: false,
maxLength: Infinity,
multiLine: false,
sanitise: true,
caretPosition: null,
tagName: 'div',
innerRef: () => { },
onBlur: () => { },
onFocus: () => { },
onKeyDown: () => { },
onPaste: () => { },
onChange: () => { },
styled: false,
};
class ContentEditable extends Component {
constructor(props) {
super();
this.state = {
value: props.content,
isFocused: false,
};
}
componentDidMount() {
this.setFocus();
this.setCaret();
}
componentWillReceiveProps(nextProps) {
if (nextProps.content !== this.sanitiseValue(this.state.value)) {
this.setState({ value: nextProps.content }, () => {
if (!this.state.isFocused) this.forceUpdate();
});
}
}
shouldComponentUpdate(nextProps) {
const propKeys = Object.keys(nextProps).filter(key => key !== 'content');
return !isEqual(pick(nextProps, propKeys), pick(this.props, propKeys));
}
componentDidUpdate() {
this.setFocus();
this.setCaret();
}
setFocus = () => {
if (this.props.focus && this._element) {
this._element.focus();
}
};
setCaret = () => {
const { caretPosition } = this.props;
if (caretPosition && this._element) {
const { value } = this.state;
const offset = value.length && caretPosition === 'end' ? 1 : 0;
const range = document.createRange();
const selection = window.getSelection();
range.setStart(this._element, offset);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
};
sanitiseValue(val) {
const { maxLength, multiLine, sanitise } = this.props;
if (!sanitise) {
return val;
}
// replace encoded spaces
let value = val.replace(/ /, ' ').replace(/[\u00a0\u2000-\u200b\u2028-\u2029\u202e-\u202f\u3000]/g, ' ');
if (multiLine) {
// replace any 2+ character whitespace (other than new lines) with a single space
value = value.replace(/[\t\v\f\r ]+/g, ' ');
} else {
value = value.replace(/\s+/g, ' ');
}
return value
.split('\n')
.map(line => line.trim())
.join('\n')
.replace(/\n{3,}/g, '\n\n') // replace 3+ line breaks with two
.trim()
.substr(0, maxLength);
}
_onChange = ev => {
const { sanitise } = this.props;
const rawValue = this._element.innerText;
const value = sanitise ? this.sanitiseValue(rawValue) : rawValue;
if (this.state.value !== value) {
this.setState({ value: rawValue }, () => {
this.props.onChange(ev, value);
});
}
};
_onPaste = ev => {
const { maxLength } = this.props;
ev.preventDefault();
const text = ev.clipboardData.getData('text').substr(0, maxLength);
document.execCommand('insertText', false, text);
this.props.onPaste(ev);
};
_onBlur = ev => {
const { sanitise } = this.props;
const rawValue = this._element.innerText;
const value = sanitise ? this.sanitiseValue(rawValue) : rawValue;
// We finally set the state to the sanitised version (rather than the `rawValue`) because we're blurring the field.
this.setState({
value,
isFocused: false,
}, () => {
this.props.onChange(ev, value);
this.forceUpdate();
});
this.props.onBlur(ev);
};
_onFocus = ev => {
this.setState({
isFocused: true,
});
this.props.onFocus(ev);
};
_onKeyDown = ev => {
const { maxLength, multiLine } = this.props;
const value = this._element.innerText;
// return key
if (!multiLine && ev.keyCode === 13) {
ev.preventDefault();
ev.currentTarget.blur();
// Call onKeyUp directly as ev.preventDefault() means that it will not be called
this._onKeyUp(ev);
}
// Ensure we don't exceed `maxLength` (keycode 8 === backspace)
if (maxLength && !ev.metaKey && ev.which !== 8 && value.replace(/\s\s/g, ' ').length >= maxLength) {
ev.preventDefault();
// Call onKeyUp directly as ev.preventDefault() means that it will not be called
this._onKeyUp(ev);
}
};
_onKeyUp = ev => {
// Call prop.onKeyDown callback from the onKeyUp event to mitigate both of these issues:
// Access to Synthetic event: https://github.com/ashleyw/react-sane-contenteditable/issues/14
// Current value onKeyDown: https://github.com/ashleyw/react-sane-contenteditable/pull/6
// this._onKeyDown can't be moved in it's entirety to onKeyUp as we lose the opportunity to preventDefault
this.props.onKeyDown(ev, this._element.innerText);
};
render() {
const { tagName: Element, content, editable, styled, ...props } = this.props;
return (
<Element
{...omit(props, Object.keys(propTypes))}
{...(styled
? {
innerRef: c => {
this._element = c;
props.innerRef(c);
},
}
: {
ref: c => {
this._element = c;
props.innerRef(c);
},
})}
style={{ minHeight: '0.28rem', minWidth: '100%', display: 'inline-block', whiteSpace: 'pre-wrap', wordWrap: 'break-word', wordBreak: 'break-all', ...props.style }}
contentEditable={editable}
key={Date()}
dangerouslySetInnerHTML={{ __html: this.state.value }}
onBlur={this._onBlur}
onFocus={this._onFocus}
onInput={this._onChange}
onKeyDown={this._onKeyDown}
onKeyUp={this._onKeyUp}
onPaste={this._onPaste}
/>
);
}
}
ContentEditable.propTypes = propTypes;
ContentEditable.defaultProps = defaultProps;
export default ContentEditable;
自适应高度文本框 react contenteditable的更多相关文章
- htm5 手机自适应问题 文本框被激活(获取焦点)时,页面会放大至原来尺寸。
加上这句话就ok啦 <meta name="viewport" content="width=device-width, initial-scale=1.0, mi ...
- html5 textarea 文本框根据输入内容自适应高度
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- jquery文本框textarea自适应高度
浏览器中默认的文本框是不能根据内容的增多变高,只能固定高度有滚动条,体验不是很好,找了很多方法兼容都不行,总算找到个兼容良好的方法: <body> <textarea id=&quo ...
- 自适应高度输入框(contenteditable/textarea)
一.用div模拟textarea div模拟输入域可以根据输入内容自动伸缩,而input和textarea输入内容较多时,高度固定,内容会显示不全. 1.坑1(IOS端无法输入) 在取消全局默认样 ...
- Jquery实现textarea根据文本内容自适应高度
本文给大家分享的是Jquery实现textarea根据文本内容自适应高度,这些在平时的项目中挺实用的,所以抽空封装了一个文本框根据输入内容自适应高度的插件,这里推荐给小伙伴们. autoTextare ...
- Jquery实现 TextArea 文本框根据输入内容自动适应高度
原文 Jquery实现 TextArea 文本框根据输入内容自动适应高度 在玩微博的时候我们可能会注意到一个细节就是不管是新浪微博还是腾讯微博在转发和评论的时候给你的默认文本框的高度都不会很高,这可能 ...
- JS案例 - 可自动伸缩高度的textarea文本框
文本框的默认现象: textarea如果设置cols和rows来规定textarea的尺寸,那么textarea的默认宽高是这俩属性设置的值,可以通过鼠标拖拽缩放文本框的尺寸. textarea如果设 ...
- [Swift通天遁地]二、表格表单-(12)设置表单文字对齐方式以及自适应高度的文本区域TextArea
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- iOS之自动调节输入文本框的高度
//自动调节输入文本框的高度 - (void)textViewDidChange:(UITableView *)textView{ float height; if ([[[UIDevice curr ...
随机推荐
- 阶段5 3.微服务项目【学成在线】_day18 用户授权_14-细粒度授权-我的课程细粒度授权-需求分析
3.3 我的课程细粒度授权 3.3.1 需求分析 1.我的课程查询,细粒度授权过程如下: 1)获取当前登录的用户Id 2)得到用户所属教育机构的Id 3)查询该教学机构下的课程信息 最终实现了用户只允 ...
- 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_09-前端显示当前用户-需求分析
登陆成功 应该要显示用户的信息 cookie只存了用户的身份令牌.不包含用户的信息 拿着短令牌 请求认证服务获取到jwt.然后存储到sessionStorage 1.用户请求认证服务,登录成功. 2. ...
- Window和Linux文件共享
一.先设置window上的目录共享 1.1.右击文件要共享的文件夹,选择属性 1.2.设置要共享给的用户和设置用户操作权限 二.安装CIFS共享服务 sudo yum -y install cifs- ...
- (十六)Centos之安装mysql
第一步:获取mysql YUM源 进入mysql官网获取RPM包下载地址 https://dev.mysql.com/downloads/repo/yum/ 点击 下载 右击 复制链接地址 https ...
- Python3之使用@property
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来简单,但是,没有办法检查参数,导致可以把成绩随便改 >>> class Student(object): ... pass ... ...
- C#登录SSH执行命令,下载文件
前言 批量登录SSH执行命令 ,把应急响应中的日志文件下载回来. 代码实现 Renci.SshNet编译出DLL,引用. using System; using System.Collections. ...
- hana客户端工具
SAP HANA可视化客户端工具是C/S模式的,远程访问使用,都不是太方便,目前有一款基于WEB的可视化工具TreeSoft,通过浏览器就可以访问使用了,并且可以同时管理.维护.监控SAP HANA等 ...
- 使用Vulcan工具构建真实的业务负载进行网络压力测试,满足SD-WAN,White-box Switch的Performance,QoE,SLA测试要求
工具链接# https://xenanetworks.com/vulcan/ 使用Vulcan工具,可构建真实的业务负载进行网络压力测试 满足Performance,QoE,SLA等测试要求 硬件指 ...
- es6 装饰器decorator的使用 +webpack4.0配置
decorator 装饰器 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码,decorator相当于一个高阶函数,接收一个函数,返回一个被 ...
- Quartz.Net入门 - Net作业调度
背景 很多时候,项目需要在不同时刻,执行一个或很多个不同的作业. Windows执行计划这时并不能很好的满足需求了,迫切需要一个更为强大,方便管理,集群部署的作业调度框架. 介绍 Quartz一个开源 ...