React,如何使使用的组件名称动态化?

时间:2020-02-13 22:24:47

标签: javascript reactjs

在React中,我有一个包装isScrolled的包装器-当页面加载时isScrolled为false,当用户滚动时,isScrolled等于true

在我的React组件之一中,我有以下内容:

    <Button.Secondary
      size="S"
      onClick={() => {
       // lots of stuff here
      }}
    >
      {!isLoggedIn ? 'XXXXX' : 'YYYY'}
    </Button.Secondary>

我面临的挑战是isScrolled为false时,我想要上面的Button.Secondary-当isScrolled为true时,我想要:

    <Button.Secondary
      size="S"
      onClick={() => {
       // lots of stuff here
      }}
    >
      {!isLoggedIn ? 'XXXXX' : 'YYYY'}
    </Button.Secondary>

如何基于isScrolled属性使Button._____动态?

3 个答案:

答案 0 :(得分:2)

假设您导入的Button只是一个看起来像这样的对象:

const Button = {
    Primary: () => return some jsx
    Secondary: () => return some jsx
}

因此,如果要渲染辅助按钮,可以执行以下操作:

  <Button.Secondary>

  // or
  const Cmp = Button.Secondary;
  return <Cmp/>

  // or
  const Cmp = Button['Secondary'];
  return <Cmp/>

外推:


import { Button } from 'somewhere'


const YourCmp = ({isScrolled}) => {

   const Cmp = Button[isScrolled ? 'Secondary' : 'Primary'];
   return <Cmp {...yourProps}><SomeChild/></Cmp>

}

答案 1 :(得分:1)

在这种情况下,以下方法是处理这种情况的方法:

~~~
const { isScrolled } = this.state;

const Btn = isScrolled ? Button.Secondary : Button.Primary;

~~~

<Btn
  size="S"
  onClick={() => {
    // lots of stuff here
  }}
>
  {!isLoggedIn ? 'XXXXX' : 'YYYY'}
</Btn>

答案 2 :(得分:1)

您可以使用辅助函数构建对象或将其作为道具传递

然后根据需要动态渲染它。

如此,例如:

import all your potential buttons 

get someLogicRelatedToScrollPosition(){
 ... take scroll position and return the name of key you want from the incoming prop

}

render(){
.... some code

/** this object might look like 
 *{
 * initial: Button.Primary,
 * scrolled: Button.Secondary,
 * someOtherScrollPosition: Button.Whatever
 * 
 *  *}
 */
const {myButtonsComponents} = this.props;
const CurrentButtonComponent = myButtonsComponents[this.someLogicRelatedToScrollPosition]


return (
  ..jsx
<CurrentButtonComponent {...props} />
)}