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

Javascript 在React中创建组件参数的最佳方法是什么?,javascript,reactjs,Javascript,Reactjs,我想创建简单、流行的组件类型:一个用于创建/更新某些业务对象的组件。当然,在这种类型的组件中,我们有两种模式:add和edit 显而易见的解决方案是属性和文本值 <Foo mode="add"/> <Foo mode="edit"/> 还有更好的办法吗?可以创建一些方便的枚举或类似的东西吗 更新 问题不在于如何实现组件模式,而在于如何更灵活地指定模式。例如,而不是 <Foo mode="add"/> <Foo mode="edit"/> 我

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

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

<Foo mode="add"/>
<Foo mode="edit"/>
还有更好的办法吗?可以创建一些方便的枚举或类似的东西吗

更新

问题不在于如何实现组件模式,而在于如何更灵活地指定模式。例如,而不是

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

我想要这样的东西:

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


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

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

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=()=>{
//在此处以样式A返回组件
}
选项B=()=>{
//在此处返回样式为B的组件
}
render(){
返回(
{this.props.mode=='add'?optionA():optionB()
)
}
通过这种方式,您可以根据传递的道具呈现任一选项。(如果“添加”,它将呈现optionA()返回的JSX,否则它将呈现optionB()的输出)

此外,这是一个非常简单的例子,我喜欢如何结构我的组件,希望在这里得到反馈

React的文档非常好,顺便说一句,你可以在这里找到更多关于条件渲染的信息:


希望这有帮助

我会做那样的事:)

导出默认类myAmazingComponent扩展组件{
建造师(道具){
超级(道具);
}
generateComponent=(模式)=>{
开关(模式){
案例“FOO”:
返回FOO模式被激活;
“酒吧”一案:
返回条模式被激活;
违约:
返回默认模式
}
}
render(){
const{mode}=this.props;
返回(
此.generateComponent(模式)
)
}
}
<Foo edit/>
<Foo add/>
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>
  )
}
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)
    )
  }
}