最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing props in a component that is stored in a variable - Stack Overflow

programmeradmin2浏览0评论

So I have a simple and straight up question.

So we can store react components in a variable. But now, I want to know if it is possible pass props to a component if it is stored in a variable?

//////////////////////////////////////////////
//////  Normal & typical React component
//////////////////////////////////////////////

const myComponent = <Hello name={'Jamie'} /> 

render () {

  return myComponent;

}


////////////////////////////////////////
//////  What I want
////////////////////////////////////////

const myComponent = <HelloWorld /> 

// I want to be able to add that props here
// something like myComponent.addProps({'name': 'jamie'});

render () {

  return myComponent;

}

My problem is well beyond just this. I wanted to know if we have such a feature in React API.

So I have a simple and straight up question.

So we can store react components in a variable. But now, I want to know if it is possible pass props to a component if it is stored in a variable?

//////////////////////////////////////////////
//////  Normal & typical React component
//////////////////////////////////////////////

const myComponent = <Hello name={'Jamie'} /> 

render () {

  return myComponent;

}


////////////////////////////////////////
//////  What I want
////////////////////////////////////////

const myComponent = <HelloWorld /> 

// I want to be able to add that props here
// something like myComponent.addProps({'name': 'jamie'});

render () {

  return myComponent;

}

My problem is well beyond just this. I wanted to know if we have such a feature in React API.

Share Improve this question edited Jan 20, 2019 at 4:45 Mansour 2044 silver badges12 bronze badges asked Jan 20, 2019 at 4:37 Jamie JamierJamie Jamier 5391 gold badge6 silver badges20 bronze badges 8
  • But why are you storing the component in a variable at all? React already does all the smart diffing for you based on what render() returns, so just use render() { return <Hello ...>; } and let React do its job. – Mike 'Pomax' Kamermans Commented Jan 20, 2019 at 4:40
  • @Mike'Pomax'Kamermans as I mentioned the problem is not just diffing and etc. I have around hundreds of components and I want to apply, filter and map these components with different logic and I want to add props completely dynamic. – Jamie Jamier Commented Jan 20, 2019 at 4:42
  • Yeah: do that in render. Generate all your components as part of your render call, and if you have hundreds of components: organise them. React is a UI library, and your UI is always reducible to "things that control a handful of other things", not hundreds of things. Use state/props for the data that you're going to generat components off of, and then build those components in render(), and let React decide whether that means it actually rebuilds them or not. That's what it's designed for. Use the key property the way it's meant to and React does the rest. – Mike 'Pomax' Kamermans Commented Jan 20, 2019 at 4:45
  • I believe you are more concerned about other stuff rather than the question. There was a reason that I eliminated other stuff and just asked this question. I just want to know if in React ecosystem and API we have such a feature. – Jamie Jamier Commented Jan 20, 2019 at 4:48
  • 1 @Mike'Pomax'Kamermans Remember you were paying attention to a lot of other details, such as diffing algorithm in React and .... By including those in question it would be more confusing.... I said and I mentioned I am targeting React API but you still were concerned about how I structure my code ...... – Jamie Jamier Commented Jan 20, 2019 at 4:56
 |  Show 3 more comments

4 Answers 4

Reset to default 17

You can try like following,

React.cloneElement(
  myComponent,
  {prop1: "prop value"}
)

Reference Doc: React Official Doc

Went through kind of same issue in typeScript, had a list of menuItem to map on it in JSX, each one containing a different React Component for icon like this:

const menuItems: {label: string, icon: React.FC, selected:boolean}[] = [
{label: 'Home', icon: <HomeIcon/>, selected: false}, 
{label: 'Live TV', icon: <ScreenIcon/>, selected: false}, 
{label: 'VOD', icon: <PlayIcon/>, selected: true},
{label: 'Podcasts', icon: <MicIcon/>, selected: false},
{label: 'Games', icon: <GameIcon/>, selected: false},
{label: 'App', icon: <MenuIcon/>, selected: false},
{label: 'Services', icon: <ShopIcon/>, selected: false},
{label: 'Languages', icon: <WorldIcon/>, selected: false},];

But I needed to give a "fill" props to the icon if the menuItem was selected or focused, so I changed my array like this:

const menuItems: {label: string, icon: React.FC, selected:boolean}[] = [
{label: 'Home', icon: HomeIcon, selected: false}, 
{label: 'Live TV', icon: ScreenIcon, selected: false}, 
{label: 'VOD', icon: PlayIcon, selected: true},
{label: 'Podcasts', icon: MicIcon, selected: false},
{label: 'Games', icon: GameIcon, selected: false},
{label: 'App', icon: MenuIcon, selected: false},
{label: 'Services', icon: ShopIcon, selected: false},
{label: 'Languages', icon: WorldIcon, selected: false},];

And Called it like this:

    const FocusableListItem: FC<ExportableProps> = (props) => {
  const classes = useStyles(props);

  return (
    <ListItem button key={props.label} className={classes.button} >
      <ListItemIcon>
        <props.icon fill={props.focused || props.selected ? '#6648ff' : '#c4c4c4'}></props.icon>
      </ListItemIcon>
      <ListItemText>{props.label}</ListItemText>
    </ListItem>
  );
};

With this kind of interface for props:

interface ExportableProps extends withFocusableProps {
  label: string;
  icon: React.FC<{fill: string}>;
  onClick?: () => void;
  disabled?: boolean;
  selected?: boolean;
  small?: boolean;
}

And works perfectly ! Don't know if it'll help someone but looks useful.

You need to Capitalize your variable name and use normal Jsx syntax:

const MyComponent = <HelloWorld /> 

render () {
  return <MyComponent name='jamie'/>
}

This is allows things like storing components in an array:

import {
  EmailShareButton,
  FacebookShareButton,
  InstapaperShareButton,
  LineShareButton,
  LinkedinShareButton,
  LivejournalShareButton,
  MailruShareButton,
  OKShareButton,
  PinterestShareButton,
  PocketShareButton,
  RedditShareButton,
  TelegramShareButton,
  TumblrShareButton,
  TwitterShareButton,
  ViberShareButton,
  VKShareButton,
  WhatsappShareButton,
  WorkplaceShareButton,
} from "react-share"

export default class LikeShare extends Component {
  shareButtons = [
    EmailShareButton,
    FacebookShareButton,
    InstapaperShareButton,
    LineShareButton,
    LinkedinShareButton,
    LivejournalShareButton,
    MailruShareButton,
    OKShareButton,
    PinterestShareButton,
    PocketShareButton,
    RedditShareButton,
    TelegramShareButton,
    TumblrShareButton,
    TwitterShareButton,
    ViberShareButton,
    VKShareButton,
    WhatsappShareButton,
    WorkplaceShareButton,
  ]

  render = () => {
    return (
      <div>
        { this.shareButtons.map(
          ShareButton => <ShareButton url={window.location.href}/>
        )}
      </div>
    )
  }
}

you can use setProps also like

myComponent.setProps({name: 'jamie'});
发布评论

评论列表(0)

  1. 暂无评论