将 prop 传递给子级的React TypeScript容器父级

umuewwlo  于 2023-01-14  发布在  TypeScript
关注(0)|答案(2)|浏览(106)

我已经尝试了几个小时,但是我还没有找到一个满意的解决方案。我想让这个 Package 器包含一些状态,然后我可以传递给它的孩子或者呈现其他东西。
我想做一些类似于这个抽象例子的事情。有什么事情沿着我可以做的吗?

const MyChild = (props:{state:boolean}) => {
   return <Text>`the state is ${props.state}`</Text>
}

const StateWrapper = ({children}:{children:React.ReactNode}) => {
   const hookState:boolean|null = useHookState()
   if (null) return <Loading />
   return {children} <-- with {state:boolean}
}

const App = () => {
   return <StateWrapper><MyChild /><StateWrapper>
}
az31mfrm

az31mfrm1#

这类问题的一个常见模式是"渲染属性"方法。"状态 Package 器"对象使用一个属性,将其数据传递给其他对象进行渲染。这样,您就不必对状态数据进行任何奇怪的更改或复制,名称也不必完全对齐,从而便于将来在其他组件中进行交换。

const MyChild = (props: {state: boolean}) => {
   return <Text>`the state is ${props.state}`</Text>
}

const StateWrapper = ({children}:{children: (state: boolean) => React.ReactNode}) => {
   const hookState:boolean|null = useHookState()
   if (null) return <Loading />
   return children(state);
}

const App = () => {
  return (
    <StateWrapper>
      {(state) => (<MyChild state={state}/>)}
    </StateWrapper>
  );
}

查看更多:https://reactjs.org/docs/render-props.html

sulc1iza

sulc1iza2#

3种类型的 Package 器,带有引用并在 typescript 中添加了属性:沙盒演示:https://codesandbox.io/s/wrapper-2kn8oy?file=/src/Wrapper.tsx

import React, { cloneElement, forwardRef, useRef, useState  } from "react";
interface MyChild extends React.ReactElement {
    ref?:React.Ref<HTMLDivElement>|undefined
}
interface MyProps {
    children:MyChild|MyChild[],
    added:string,
}

const Wrapper1 = ({ children, added }: MyProps) => {
    const e =
        Array.isArray(children) ?
            children.map((child) => {
                return cloneElement(child, { added: added })
            }) :
            cloneElement(children)
    return <>
        {e}
    </>
}

const Wrapper2 = ({ children, added }:MyProps) => {

    const e =
        Array.isArray(children) ?
            children.map((child) => {
                return <child.type  {...child.props} added={added} ref={child.ref} />
            }) :
            children?<children.type {...children.props} added={added} ref={children.ref}/>:null
    //console.log("2:",e)
    if(!Array.isArray(children))console.log(children.ref)
    return <>
        {e}
    </>
}
const Wrapper3 = ({ children, added }:{children:any,added:any}) => {
    return <>
        {children(added)}
    </>
}

const Mydiv = forwardRef((props: any, ref?: any) =>
    <div ref={ref}>Origin:{props.message},Added:{props.added ?? "None"}</div>
)
const Container = () => {
    const ref1 = useRef<HTMLDivElement>(null)
    const ref2 = useRef<HTMLDivElement>(null)
    const ref3 = useRef<HTMLDivElement>(null)
    const [refresh, setRefresh] = useState(1)
    const setColor = () => {
        console.log("ref1:", ref1.current, "ref2:", ref2.current, "ref3:", ref3.current)
        if (ref1.current) ref1.current.style.color = "red"
        if (ref2.current) ref2.current.style.color = "red"
        if (ref3.current) ref3.current.style.color = "red"
    }

    return <>
        <button onClick={setColor}>Change Color</button>
        <button onClick={() => setRefresh((n) => n + 1)}>Refresh page</button>
        <div>{`state:${refresh}`}---state:{refresh}</div>

        <Wrapper1 added="Wrapper1 added">
            <Mydiv ref={ref1} message={`MyDiv 1 with Ref,parent state:${refresh}`} />
            <Mydiv message={`MyDiv 1 without ref,parent state:${refresh}`} />
        </Wrapper1>

        <Wrapper2 added="Wrapp2 added">
            <Mydiv ref={ref2} message={`MyDiv 2 with Ref,parent state:${refresh}`} />     
            <Mydiv message={`MyDiv 2 without ref,parent state:${refresh}`} />
        </Wrapper2>

        <Wrapper3 added="Wrapp3 added">
            {(added: any) => (<>
                <Mydiv ref={ref3} message={`MyDiv 3 with Ref,parent state:${refresh}`} added={added} />
                <Mydiv message={`MyDiv 3 without Ref,parent state:${refresh}`} added={added} />
            </>
            )}
        </Wrapper3>

    </>
}
export default Container

相关问题