Reactjs基于jsx中的属性创建条件组件

Reactjs creating conditional components bases on properties in jsx?

本文关键字:创建 条件 组件 属性 基于 jsx Reactjs      更新时间:2024-03-09

/*问题是根据props值返回输入或文本区域,但两者都应该包含公共props*/

var Textinput = React.createClass({
  render: function() {        
    /* input or textarea based on props */
    _startElm(this.props.elm) /* input or textarea (with distinct prop) */
    ......
    /* commmon props */
    ......
    _closeElm()
    return (_startElm + common_props + _closeElm);
  }
});

您可以执行类似的操作

 var TestApp = React.createClass({
    render: function(){
      var props = {id: 'one', class: 'two', value: 'three', type: 2};
      var el;
      if(props.type == 1){
        el = (<input type="text" defaultValue={props.value} />);
      }else{
        el = (<textarea defaultValue={props.value} />);
      }
      return(
           <div>{el}</div>
      );
    }
  });
  React.renderComponent(<TestApp />, document.getElementById('main'));

这是演示

希望这能有所帮助。

您不能像React中那样构建组件的渲染。。。为了获得最佳的开发和运行时行为,您需要一次将所有属性设置到一个新组件中,而不是将其构建成碎片。

正如您将在下面看到的,我已经简化了代码,以便根据我称为inputType的属性有条件地返回不同的组件。

我还利用了JSX编译器的一个叫做spread attributes的特性。快速总结是,它将把主机对象中的所有属性复制到目标中。而且,在React组件(如textarea)的情况下,它复制对该元素有效的所有属性。它很方便。但是,您没有必要使用它,您可以选择手动指定特定的属性。

var Textinput = React.createClass({            
  render: function() {        
    // input or textarea based on props called inputType
    if (this.props.inputType === 'textarea') {
        // using the spread attributes feature of JSX ({...this.props}), which 
        // will copy all valid properties into the DOM element
        return <textarea {...this.props} />;
    } 
    return <input type="text" {...this.props} />;       
  }
});

你也可以使用破坏任务(记录在上面链接的同一页面上):

var { inputType, ... props } = this.props;
if (inputType === 'textarea') {
    // notice it's now referring to just a local object called props
    return <textarea {...props} />;

通过使用{ inputType, ... props}破坏语法,编译器创建了两个局部变量inputTypepropsinputType将被设置为this.props.inputType的值,而props变量将被分配给this.prop的所有其他属性,属性inputType除外。