首先每个emoji 表情有保存到服务器,可以通过 URL 访问,如
http://....../em001
1.将带 emoji 标签复合文本字符串(如:你好,em001),分割成纯文本和 emoji 标签文本,并装进数组。方法如下
/**
根据说说内容,将文本、表情切分为数组
@param {string} content 说说源内容
*/
function messageContentArray (content) {
const reg = /\[em[2-4]+\d{3}\]/g;
const emRegArr = content.match(reg);
// 没有表情,直接返回文本内容
if (!emRegArr) return [{type: 'text', content}];
const indexArr = [];
const contentArr = [];
// 递增取得所有表情index
let pos = content.indexOf(emRegArr[0]);
for (let i = 1; i < emRegArr.length; i++) {
indexArr.push(pos);
pos = content.indexOf(emRegArr[i], pos + 1);
}
indexArr.push(pos);
indexArr.map((emIndex, i) => {
// 首个为表情
if (emIndex === 0) {
contentArr.push({type: 'emotion', source: emRegArr[i]});
} else {
if (i === 0) {
// TODO:临时的处理方式,待观察内存占用情况
for (let index = 0; index < emIndex; index++) {
contentArr.push({type: 'text', content: content[index]});
}
// contentArr.push({type: 'text', content: content.substr(0, emIndex)});
} else {
// 两个表情之间夹杂了文本
const preEmoLocation = indexArr[i - 1] + emRegArr[i - 1].length;
const locationDiff = emIndex - preEmoLocation;
if (locationDiff > 0) {
for (let index = preEmoLocation; index < locationDiff; index++) {
contentArr.push({type: 'text', content: content[index]});
}
// contentArr.push({type: 'text', content: content.substr(preEmoLocation, locationDiff)});
}
}
contentArr.push({type: 'emotion', source: emRegArr[i]});
}
});
const lastLocation = indexArr[indexArr.length - 1] + emRegArr[emRegArr.length - 1].length;
if (content.length > lastLocation) {
// contentArr.push({type: 'text', content: content.substr(lastLocation, content.length - lastLocation)});
for (let index = lastLocation; index < content.length; index++) {
contentArr.push({type: 'text', content: content[index]});
}
}
return contentArr;
}
2.然后在 view 标签,遍历数组
<View className="talk-content">
{contentArr.map((Citem, index) => {
if (Citem.type === 'emotion') {
const str = Citem.source.substr(1, Citem.source.length-2);
return <Image key={`Emotion_${index}`} className="emoji" src={'http://'+str+'.jpg'} />;
}
const isEnter = Citem.content === '\n';
if (isEnter) {
// hack Text 显示单个 \n 时,会有样式问题
return <View key={`Text_${index}`} />;
}
return <Text key={`Text_${index}`} className="txt" >{Citem.content}</Text>;
})}
</View>
网友评论