是否可以将组件作为属性传递并向其添加交互?

时间:2018-01-26 15:46:44

标签: reactjs

我有以下课程,应该处理模态

class Modal extends React.Component {
   constructor(props){
      this.confirmBtn = props.confirmBtn || <button type="button">Confirm</button>
      this.cancelBtn = props.confirmBtn || <button type="button">Cancel</button>
   }

   render(){
       return (<div>
       {this.props.children}

       <div>{this.confirmBtn} {this.cancelBtn}</div>
       </div>);

   }
}

由于这些按钮是组件,它们可以做他们应该做的任何事情,但我想要做的是添加关闭模态的额外功能。

理想情况下,我想要这样的事情:

伪代码

render(){
   const ConfirmBtn = this.props.confirm;
   const CancelBtn = this.props.cancel;
   return (<div>
       {this.props.children}

       <div>
          <ConfirmBtn onClick={this.close.bind(this)}/> 
          <CancelBtn onClick={this.close.bind(this)}/>
       </div>);
}

我知道可以在内部保留按钮并为它们添加回调,但我只是想知道在React中是否可以做这件事。

1 个答案:

答案 0 :(得分:1)

假设this.props.confirmthis.props.cancel组件而非元素,您的代码将正常运行。例如,Modal将是一个组件,但<Modal/>是一个元素。

那就是说,我个人并不是以这种方式传递组件的粉丝。虽然它可以正常工作,但您不会强制限制允许为confirmcancel传入哪种类型的Component。想象一下,传入一个textbox组件。或者按钮样式不正确占用了太多空间并破坏了模态其余部分的样式。  它会渲染,但是.... eugh。

当然,人体测试应该能够解决这些问题。但如果我们需要依靠一个真正的人类,那么我们就容易受到人为错误的影响。我们都讨厌人为错误,对吗?

相反,我建议制作一个名为buttonType的道具。使用此prop作为枚举,可以在您可能希望使用的各种按钮组件之间进行选择。有默认值。 e.g。

getButtonComponent() {
    switch( this.props.buttonType ) {
        case 'someType': return SomeType;
        case 'anotherType': return AnotherType;
        default: return DefaultType;
    }
}

render() {
    const ConfirmButton = this.getButtonComponent();
    const CancelButton = this.getButtonComponent();
    ...