Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Is it possible to write universal component? (react/typescript)

Is it possible to write universal component? which receives some object with similar data (for example: id, title, text, date) and renders it. But all objects have different keynames. Three objects for example, all of them have id, title, text, and date:

obj1 {id: 1, textVar: 'textString1', titleVar: 'titleString1', date1: '2000-10-10'}

obj2 {id: 2, title2: 'titleString2', someDate: '2001-11-11', otherTextVar: 'textString2'}

obj3 {id: 3, otherText3: 'textString3', otherDate: '2000-10-10', newsTitle: 'titleString3'}

Is it possible to write universal component, wich can work with any of objects?

interface UCompProps {
    id: number,
    title: string,
    text: string,
    date: string,
  }, 
}

const UComponent: React.FC<UCompProps> = (props) => {
  const { id, title, text, date } = props;
  return (
    <>
      <div>{id}</div>
      <div>{title}</div>
      <div>{text}</div>
      <div>{date}</div>
    </>
  )
}

export default UCompProps

Have no idea how to do it. Any advice how to do it?

question from:https://stackoverflow.com/questions/65883426/is-it-possible-to-write-universal-component-react-typescript

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

1 Answer

0 votes
by (71.8m points)

If you know structures of all objects, then you can map array of that objects.

// in parent:
return (
  <div>
    {arrayOfobjects1
      .map(obj1=>({
        id:obj1.id, title:obj1.titleVar , text:obj1.textVar, date: obj1.date1
      }))
      .map(props=><Ucomponent key={props.id} {...props} />)
    }
  </div>
)

And also you can define that mapping functions for each types of objects:

// in parent:

const mapper1 = object1 => ({id:obj1.id, title:obj1.titleVar, text:obj1.textVar, date: obj1.date1});

return (
  <div>
    {arrayOfobjects1
      .map(mapper1)
      .map(props=><Ucomponent key={props.id} {...props} />)
    }
  </div>
)

Or you can render them all together after mapping of each array

const arrayToRender = [...arr1.map(mapper1), ...arr2.map(mapper2), ...arr3.map(mapper3)];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...