首页 > 其他分享 >[React] Compound Pattern

[React] Compound Pattern

时间:2022-08-26 19:58:01浏览次数:74  
标签:function const FlyOut Pattern React Compound return children

Source : https://javascriptpatterns.vercel.app/patterns/react-patterns/compound-pattern

 

A compound compoennt usage looks like this:

import React from "react";
import { FlyOut } from "./FlyOut";

export default function SearchInput() {
  return (
    <FlyOut>
      <FlyOut.Input placeholder="Enter an address, city, or ZIP code" />
      <FlyOut.List>
        <FlyOut.ListItem value="San Francisco, CA">
          San Francisco, CA
        </FlyOut.ListItem>
        <FlyOut.ListItem value="Seattle, WA">Seattle, WA</FlyOut.ListItem>
        <FlyOut.ListItem value="Austin, TX">Austin, TX</FlyOut.ListItem>
        <FlyOut.ListItem value="Miami, FL">Miami, FL</FlyOut.ListItem>
        <FlyOut.ListItem value="Boulder, CO">Boulder, CO</FlyOut.ListItem>
      </FlyOut.List>
    </FlyOut>
  );
}

 

We can implement the Compound pattern using either a Provider, or React.Children.map.

Provider (preferred)

The FlyOut compound component consists of:

  • FlyoutContext to keep track of the visbility state of FlyOut
  • Input to toggle the FlyOut's List component's visibility
  • List to render the FlyOut's ListItemss
  • ListItem that gets rendered within the List.
const FlyOutContext = React.createContext();

export function FlyOut(props) {
  const [open, setOpen] = React.useState(false);
  const [value, setValue] = React.useState("");
  const toggle = React.useCallback(() => setOpen((state) => !state), []);

  return (
    <FlyOutContext.Provider value={{ open, toggle, value, setValue }}>
      <div>{props.children}</div>
    </FlyOutContext.Provider>
  );
}

function Input(props) {
  const { value, toggle } = React.useContext(FlyOutContext);

  return <input onFocus={toggle} onBlur={toggle} value={value} {...props} />;
}

function List({ children }) {
  const { open } = React.useContext(FlyOutContext);

  return open && <ul>{children}</ul>;
}

function ListItem({ children, value }) {
  const { setValue } = React.useContext(FlyOutContext);

  return <li onm ouseDown={() => setValue(value)}>{children}</li>;
}

FlyOut.Input = Input;
FlyOut.List = List;
FlyOut.ListItem = ListItem;

 

React.Children.map

export function FlyOut(props) {
  const [open, setOpen] = React.useState(false);
  const [value, setValue] = React.useState("");
  const toggle = React.useCallback(() => setOpen((state) => !state), []);

  return (
    <div>
      {React.Children.map(props.children, (child) =>
        React.cloneElement(child, { open, toggle, value, setValue })
      )}
    </div>
  );
}

function Input(props) {
  const { value, toggle } = React.useContext(FlyOutContext);

  return <input onFocus={toggle} onBlur={toggle} value={value} {...props} />;
}

function List({ children }) {
  const { open } = React.useContext(FlyOutContext);

  return open && <ul>{children}</ul>;
}

function ListItem({ children, value }) {
  const { setValue } = React.useContext(FlyOutContext);

  return <li onm ouseDown={() => setValue(value)}>{children}</li>;
}

FlyOut.Input = Input;
FlyOut.List = List;
FlyOut.ListItem = ListItem;

 

标签:function,const,FlyOut,Pattern,React,Compound,return,children
From: https://www.cnblogs.com/Answer1215/p/16629011.html

相关文章

  • [Javascript] Prototype Pattern
    Source:https://javascriptpatterns.vercel.app/patterns/design-patterns/prototype-pattern Ifyouusefactorypatterntocreateobject:constcreateDog=(nam......
  • [React] SWR for data fetching
    DocsThename“SWR”isderivedfrom stale-while-revalidate,aHTTPcacheinvalidationstrategypopularizedby HTTPRFC5861.SWRisastrategytofirstret......
  • [Javascript] Factory pattern vs Class instance
    InJavaScript,thefactorypatternisn'tmuchmorethanafunctionthatreturnsanobjectwithoutusingthe new keyword. ES6arrowfunctions allowustocr......
  • react中CodeMirror (代码编辑器)
    前言:实现一个在react项目中页面展示代码编辑器的效果。codemirror:使用JavaScript为浏览器实现的多功能文本编辑器。codemirror作用:专门用于编辑代码,并带有实现......
  • [Javascript] Singleton Pattern
    Source:https://javascriptpatterns.vercel.app/patterns/design-patterns/singleton-patternWiththeSingletonPattern,werestricttheinstantiationofcertainc......
  • React报错之You provided a `checked` prop to a form field
    正文从这开始~总览当我们在多选框上设置了checked属性,却没有onChange处理函数时,会产生"Youprovideda checked proptoaformfieldwithoutan onChange handle......
  • 记录一下react遇到的初始化异步赋值问题
    组件加载时发送接口请求获取数据,在根据收集到的数据的某一项值在进行请求获取相对应的值,实现联动效果1useEffect(()=>{2//getQuestionDetail({id:'61a78f5......
  • react 二级路由嵌套
    嵌套路由之后,静态文静路径错误,更改webpack 打包output输出根目录,publicPath:'/',二级路由刷新之后白屏,在首页模板文件中路径前加  /,   ......
  • localStorge在react中的使用
    1.什么时候用,在哪里用刚获取数据的时候,进行设置,localStorge.setItem(key,value);因为localStorge是用来作为缓存的,且有一定的延时,尤其是在本页面设置本页面使用时,所以,依然......
  • npm+react linux 开荒
    安装npmyuminstallnodejs.x86_64yuminstallnpm.x86_64 更新GCC版本(参考链接:https://blog.csdn.net/qq_39715000/article/details/120703444)升级到gcc7.3yum-y......