Reactjs基于jsx中的属性创建条件组件
Reactjs creating conditional components bases on properties in jsx?
/*问题是根据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}
破坏语法,编译器创建了两个局部变量inputType
和props
。inputType
将被设置为this.props.inputType
的值,而props
变量将被分配给this.prop
的所有其他属性,属性inputType
除外。
相关文章:
- 我已经创建了一个jquery转盘,并使用if条件来运行和停止转盘
- 如果满足某些条件,我如何才能创建一个只有值的对象
- Javascript-在一个数组中搜索整个单词,并创建一个符合条件的新数组
- 有条件地创建ajax url参数以与jQuery Validate一起使用
- jqGrid有条件地创建一列
- Reactjs基于jsx中的属性创建条件组件
- Angular2-对有条件创建的输入字段进行表单验证
- 如何在单选按钮中创建条件?(在jQuery Ajax中)
- 如何在单选按钮上创建条件
- 在 $.each 函数中使用条件来创建数组
- 如何在量角器中为元素存在或不存在创建条件
- 我想添加条件以更改此脚本中的图像或创建新的图像
- 从 ASP.NET Web 窗体中的服务器端属性创建 JavaScript 条件
- 如何有条件地验证在 Oracle Application Express 中的项目上创建的验证
- 如何在jquery onchange事件中创建条件
- 如何使用JQuery创建条件下拉菜单
- 如何在HTML中创建条件超链接
- 基于页面URL创建条件语句
- 如何在meteor上创建条件,将admin角色分配给新用户
- 如何在 Jade 模板中创建条件表单值