乐闻世界logo
搜索文章和话题

How to pass more than 1 ref to a child component in SolidJS?

1个答案

1

In SolidJS, ref is a special attribute used to obtain the actual DOM reference of a component or element. If you need to pass multiple ref to child components, you can achieve this through several different approaches.

Method One: Passing each ref individually

This is the most straightforward approach. You can define a separate prop for each required ref in the child component and use these ref within the child component.

Parent Component:

jsx
import { createSignal, createEffect, createRef } from 'solid-js'; import ChildComponent from './ChildComponent'; function ParentComponent() { const ref1 = createRef(); const ref2 = createRef(); createEffect(() => { console.log(ref1.current); // Access the DOM of ref1 console.log(ref2.current); // Access the DOM of ref2 }); return ( <ChildComponent ref1={ref1} ref2={ref2} /> ); }

Child Component:

jsx
function ChildComponent(props) { return ( <div> <div ref={props.ref1}>Element 1</div> <div ref={props.ref2}>Element 2</div> </div> ); }

Method Two: Using an object to wrap multiple ref

When dealing with multiple ref, you can wrap them in an object and pass this object as a single prop to the child component.

Parent Component:

jsx
import { createSignal, createEffect, createRef } from 'solid-js'; import ChildComponent from './ChildComponent'; function ParentComponent() { const refs = { ref1: createRef(), ref2: createRef() }; createEffect(() => { console.log(refs.ref1.current); // Access the DOM of ref1 console.log(refs.ref2.current); // Access the DOM of ref2 }); return ( <ChildComponent refs={refs} /> ); }

Child Component:

jsx
function ChildComponent(props) { return ( <div> <div ref={props.refs.ref1}>Element 1</div> <div ref={props.refs.ref2}>Element 2</div> </div> ); }

Choosing the Best Method

  • If only a few ref need to be passed, the first method (passing each ref individually) is simpler and more intuitive.
  • If you have multiple ref or anticipate adding more in the future, the second method (using an object to wrap) keeps the code cleaner and easier to manage.

Both methods effectively pass multiple ref to child components. Choose based on your specific requirements and preferences. In practice, evaluate the current complexity of your component and future maintenance needs to decide which approach to use.

2024年7月23日 13:37 回复

你的答案