ค้นหาเว็บไซต์

javascript - วิธีสร้างตัวห่อที่เปลี่ยน props สำหรับคอมโพเนนต์ใน react


ฉันกำลังพยายามทำบางอย่างกับคอมโพเนนต์ของ React เป็นครั้งแรกและต้องการความช่วยเหลือจากคุณ ฉันต้องการห่อคอมโพเนนต์หนึ่งภายในอีกคอมโพเนนต์หนึ่งแบบไดนามิกและเปลี่ยน props ของมัน ตัวอย่างเช่น สมมติว่าฉันมีคอมโพเนนต์นี้:

สมมติว่าฉันต้องการส่ง key3 จากตัวห่อ

หมายเหตุ: การใช้ React-Native กับ TypeScript

type Props { key1: string, key2: string, key3: any }
const FirstComponent = ({ key1, key2, key3 }:Props) => {
   return <View>
    <Text>{key1} and {key2} with {key3}</Text>
<View/>
}

ตัวอย่างตัวห่อ

const FirstComponentWrapper = (props:Props) => {
 const value = 'something';
  return <FirstComponent {...props} key3={value} />
}

ตัวห่อที่นี่ช่วยให้คอมโพเนนต์สามารถเข้าถึงค่าของ key3 ได้ ถ้าฉันมีแอปขนาดใหญ่ที่มีคอมโพเนนต์เยอะ ๆ และฉันไม่สามารถสร้างมันได้ทุกครั้ง ดังนั้นฉันกำลังมองหาวิธีสร้างตัวห่อที่ไหนสักแห่งเพื่อให้ฉันสามารถเรียกใช้งานได้ง่าย

ตัวอย่าง :

type Props = {
  component: React.ReactNode // not just function component it can be also class 
                             // component ;
  newValue: any;
}
export const Wrapper = ({ component, newValue }:Props) => {
  // this is what I missed
  // looking to return any passed component here as in the example I mentioned with new 
  // value that's added to the prop
}

มีใครช่วยได้ไหม? ขอบคุณล่วงหน้า.

คำตอบ #1

คุณสามารถใช้ children ใน Props เพื่อเรนเดอร์คอมโพเนนต์ที่ห่อของคุณด้วยคอมโพเนนต์ Wrapper

type Props = {
  children: React.ReactNode 
  newValue: any;
}
export const Wrapper = ({ children, newValue, ...otherProps }: Props) => {
  return React.cloneElement(children, {...otherProps, key3: newValue})
}

การใช้งาน

<Wrapper newValue="value3">
  <FirstComponent key1="value1" key2="value2" />
</Wrapper>

อีกวิธีหนึ่ง คุณสามารถมีคอมโพเนนต์ลำดับสูง (HOC) เพื่อปรับแต่ง props ของคุณก่อนที่คอมโพเนนต์ที่ห่อไว้นั้นจะถูกเรนเดอร์

const withModifiedProps = (WrappedComponent: React.ReactNode) => {
   const Wrapper = ({ newValue, ...props }) => {
      return <WrappedComponent {...props} key3={newValue} />
   }
   return Wrapper
}

หลังจากนั้น คุณสามารถห่อส่วนประกอบของคุณด้วย HOC

export default withModifiedProps(FirstComponent)

ทุกครั้งที่คุณเรนเดอร์ FirstComponent คุณสามารถส่งค่า newValue ให้กับมันได้ ซึ่งจะทำการเติมค่า key3 ให้โดยอัตโนมัติแทน newValue

<FirstComponent key1="value1" key2="value2" newValue="value3" />