繁体   English   中英

在React中创建组件参数的最佳方法是什么?

[英]What is the best way to create parameter of the component in React?

我想创建一种简单而流行的组件类型:一种用于创建/更新某些业务对象的组件。 当然,在这种类型的组件中,我们有两种模式: addedit

显而易见的解决方案是属性和文本值。

<Foo mode="add"/>
<Foo mode="edit"/>

我在想是否有任何整洁的方式公开模式,以便开发人员可以从某些指定的值中进行选择?

我试图找到一些例子,但是这种“文本参数”方法似乎很流行。 例如,在材料ui模式/按钮类型中,是以相同的方式完成的( variant属性):

<Button variant="fab" color="secondary" aria-label="Edit" className={classes.button}>
    <Icon>edit_icon</Icon>
</Button>
<Button variant="extendedFab" aria-label="Delete" className={classes.button}>
    <NavigationIcon className={classes.extendedIcon} />
    Extended
</Button>

有什么更好的办法吗? 是否可以创建一些方便的枚举或类似的东西?

更新

问题不在于如何实现组件模式,而在于如何更整洁地指定模式。 例如代替

<Foo mode="add"/>
<Foo mode="edit"/>

我想要这样的东西:

<Foo mode={FooModes.add}/>
<Foo mode={FooModes.edit}/>

要么

<Foo edit/>
<Foo add/>

我会那样做的:)

export default class myAmazingComponent extends Component {

  constructor(props) {
    super(props);
  }

  generateComponent = (mode) => {
    switch(mode) {
      case 'FOO' :
        return <div>FOO Mode is activated</div>;
      case 'BAR' :
        return <div>BAR Mode is activated</div>;
      default:
        return <div>DEFAULT mode</div>
    }
  }

  render() {
    const { mode } = this.props;
    return (
      this.generateComponent(mode)
    )
  }
}

我不确定我是否正确理解了您的问题,但是在我看来,您正在尝试有条件地渲染某些内容。

我通常要做的是在自己的类属性/方法中包含两种类型的内容,如下所示:

optionA = () => {
  // return the component in style A here
}
optionB = () => {
  // return the component in style B here
}

render() {
  return(
    <div>
      {this.props.mode === 'add' ? optionA() : optionB()
    </div>
  )
}

这样,您可以根据传递的道具来渲染任一选项。 (如果“添加”,它将呈现由optionA()返回的JSX,否则将呈现optionB()的输出)

同样,这是一个非常简单的示例,说明了我喜欢如何构造组件,希望在这里提供反馈!

顺便说一句,React的文档真的很棒,您可以在这里找到更多关于条件渲染的信息: https : //reactjs.org/docs/conditional-rendering.html

希望这有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM