/ *问题是根据道具值返回输入或textarea,但两者都应包含常见的道具* /
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);
}
});
答案 0 :(得分:0)
你可以做这样的事情
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'));
这是DEMO
希望这有帮助。
答案 1 :(得分:0)
您无法像React中那样构建组件的渲染...为了获得最佳的开发和运行时行为,您需要将所有属性一次性设置为新组件而不是构建它碎片。
正如您将在下面看到的,我已经简化了代码,以根据我称为inputType
的属性有条件地返回不同的组件。
我还利用了名为spread attributes的JSX编译器的一个特性。快速摘要是它将所有属性从主机对象复制到目标。并且,对于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
的所有其他属性,不包括属性{ {1}}。