[英]React - how to implement a page-wide manipulation?
我需要实现一个页面范围的字典(对于站点中的每个页面),以便当出现在字典中的单词悬停时,旁边会出现一个带有定义的小框。
一种方法是使用一个组件来包装站点中的每个文本,该组件在文本上循环并添加所需的效果。
但是,使用 jQuery,我可以通过循环页面中所有文本的页面范围操作以更少的工作来完成。
有没有一种 coorect 方法可以在 React 中实现页面范围的操作?
是否可以(即推荐)混合使用 react 和 jQuery
谢谢
一种反应式方法的粗略概述:
拥有顶级组件Dictionary
,它呈现一个Provider
的函数,该函数允许使用上下文的其他组件在字典中查找单词。
创建一个组件Explanation
,它使用Dictionary
提供的上下文并检查单词的描述是否存在,如果存在,则在悬停时呈现弹出窗口。
例子:
const tokenize = (text, dictionary) => {
return text
.split(/(\b\w+\b)/gi)
.map(word => {
const description = dictionary[word];
if (!description) return word;
return (
<span title={description} className="dashed">
{word}
</span>
);
})
.reduce((acc, current, idx) => {
if (typeof acc[acc.length - 1] === 'string' && typeof current === 'string') {
acc[acc.length - 1] += current;
return acc;
}
acc.push(current);
return acc;
}, []);
};
const DictionaryContext = createContext({getDescription: () => null});
// holds the words and exposed function to look a word up
const Dictionary = ({words, children}) => {
const getTokens = useCallback(text => tokenize(text, words), [words]);
return <DictionaryContext.Provider value={{getTokens}}>{children}</DictionaryContext.Provider>;
};
// gets the explanation from the context and renders it as a title
const Explanation = ({children}) => {
const {getTokens} = useContext(DictionaryContext);
if (!children) return null;
return getTokens(children);
};
现场示例:
但是您仍然需要将整个文本包装成一个组件。 这是由于 react 的工作原理。 它是声明性的,因为它描述了在编译时显示数据的所有可能方式。 但实际上我发现这是更好的设计,因为你应该明确地将文本标记为可能有解释。
是否可以(即推荐)混合使用 react 和 jQuery
这是可能的,但由于概念根本不同,我会尽量避免这种情况。 React 保留了 DOM 的内部表示,如果它是从外部通过例如 jQuery 进行操作的,它可能会产生难以解决的意外结果。 React ans jQuery 绝对不适合。
编辑:
这是相同代码的更强大的版本(感谢@Elia Weiss),它支持:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.