实际上目前react-native-highlight-words 只是highlight-words-core 的一个react-native 包装器。它提供了一个在 react-native 中使用的组件。我检查了它的库,没有onPress 事件附加到 react-native-highlight-words 中的Text 组件。
如果要执行onPress,则必须在react-native-highlight-words 的核心库中编写onpress 函数。
在Highlighter.js中新建两个onPress函数,
Highlighter.propTypes = {
...
...
onPressNormalText: PropTypes.func,
onPressHighlightedText: PropTypes.func
};
然后在 Highlighter 中添加这个 onPress 函数为,
export default function Highlighter({..., ..., onPressNormalText, onPressHighlightedText}) {
...
...
...
}
最后在Highlighter.js的Text组件上添加这个函数,
return (
<Text style={style} {...props} onPress={onPressNormalText}>
{chunks.map((chunk, index) => {
const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);
return !chunk.highlight ? (
text
) : (
<Text onPress={onPressHighlightedText} key={index} style={chunk.highlight && highlightStyle}>
{text}
</Text>
);
})}
</Text>
);
所以最后你的Highlighter.js 和onPress 事件看起来像,
import React from "react";
import { Text, TouchableOpacity } from "react-native";
import { findAll } from "highlight-words-core";
import PropTypes from "prop-types";
Highlighter.propTypes = {
autoEscape: PropTypes.bool,
highlightStyle: Text.propTypes.style,
searchWords: PropTypes.arrayOf(PropTypes.string).isRequired,
textToHighlight: PropTypes.string.isRequired,
sanitize: PropTypes.func,
style: Text.propTypes.style,
onPressNormalText: PropTypes.func,
onPressHighlightedText: PropTypes.func
};
/**
* Highlights all occurrences of search terms (searchText) within a string (textToHighlight).
* This function returns an array of strings and <Text> elements (wrapping highlighted words).
*/
export default function Highlighter({
autoEscape,
highlightStyle,
searchWords,
textToHighlight,
sanitize,
onPressNormalText,
onPressHighlightedText,
style,
...props
}) {
const chunks = findAll({ textToHighlight, searchWords, sanitize, autoEscape });
return (
<Text style={style} {...props} onPress={onPressNormalText}>
{chunks.map((chunk, index) => {
const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);
return !chunk.highlight ? (
text
) : (
<Text onPress={onPressHighlightedText} key={index} style={chunk.highlight && highlightStyle}>
{text}
</Text>
);
})}
</Text>
);
}
现在你可以使用Highlighter.js作为,
<Highlighter
highlightStyle={{ backgroundColor: "yellow" }}
searchWords={["and", "or", "the"]}
textToHighlight="The dog is chasing the cat. Or perhaps they re just playing?"
onPressNormalText={() => console.log("normal text is clickeddd!")}
onPressHighlightedText={() => console.log("highlighted text is clickked!")
/>
一切都完成了:)
或者如果你不想做这一切,只需使用我的这个库的分叉版本,https://github.com/adityasonel/rn-highlight-words