Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

reactjs - React: Design pattern that uses a Ref to set style of the parent component

I would like to ask if this is a sensible component design pattern in React.

Let's say I have the following components, App, ContentContainer and WithBlueBackground. The idea is to use a Ref to set a blue background on the ContentContainer with the WithBlueBackground component.

The simplified code would look something like this.

// App.js
export function App() => {
  const contentContainerRef = useRef();

  return (
    <ContentContainer contentContainerRef={contentContainerRef}>
      <WithBlueBackground contentContainerRef={contentContainerRef}>
      </WithBlueBackground>
    </ContentContainer>
  )
} 
// ContentContainer
export function ContentContainer(props) => {
  return (
    <div ref={props.contentContainerRef}>
      // Some content     
    </div>
  )
} 
// WithBlueBackground
export function ContentContainer(props) => {
  useEffect(() => {
    if (props.containerRef && props.contentContainerRef.current) {
      props.contentContainerRef.current.style.backgroundColor = 'blue';
    }
  }, [props.contentContainerRef])

  return <>{ props.children }</>;
} 

This way if I want to have a green background in the content container I can create a new component that sets this style without the ContentContainer having to know about this. This increases the composability of the code which is promote in the react docs.

Nevertheless, passing the refs is a bit ugly.

My question is, is this a sensible pattern and if not is there another way to achieve what I am trying to do here.

question from:https://stackoverflow.com/questions/65922169/react-design-pattern-that-uses-a-ref-to-set-style-of-the-parent-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If it is a direct child, you could just pass an update function around:

// ContentContainer
export function ContentContainer(props) {
  const [backgroundColor, setColor] = React.useState("white");

  return (
    <div style={{ backgroundColor }}>
      <ChildComponent setColor={color => setColor(color)}>// Some content</ChildComponent>;
    </div>
  );
}

// WithBlueBackground
export function ChildComponent(props) {
  React.useEffect(() => {
    props.setColor("blue");
  }, []);

  return <>{props.children}</>;
}

If it is deeper nested, you could use the context API. The same principle applies.enter link description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...