所以我有一个函数来过滤传递的参数是否是select,text或date字段,并且是动态地添加到render jsx。
当我触发返回时,它不会渲染html / jsx。我已经在console.logs中测试而不是html并且它成功告诉我switch语句的结构是正确的并且我传递了正确的类型,只是html返回不想呈现。没有警告或错误。当我在console.log中得到checkType函数
没有警告或错误。
以下是this.getFields()
验证
// wrapped in a react class
checkType(type, options, placeholder, name, handleUpdatedValue, defvalue, index) {
let select = <select onChange={handleUpdatedValue.bind(this)} >{options.map((option, i) => <option value={option} key={i}>{option}</option>)}</select>;
let text = <input onChange={handleUpdatedValue.bind(this)} name={name} placeholder={placeholder} type="text" />
let date = <input onChange={handleUpdatedValue.bind(this)} name={name} placeholder={placeholder} type="date" />
switch(type) {
case 'select':
return select
break;
case 'text':
return text
break;
case 'date':
return date
break;
default:
console.log('Error: Invalid Type');
}
}
handleSubmit() {
}
render() {
let values = this.state.fieldValues;
const checkType = this.checkType.bind(this);
return(
<div className="formwrapper thinshadow">
<h3>{this.props.header}</h3>
{this.getFields().map((field, i) => {
<div key={i} className={field.classes}>
{checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)}
<div className="minilabel"></div>
</div>
})}
<button className="btn btn-primary"
onClick={() => this.props.onClick(values)} >
Save
</button>
</div>
);
}
答案 0 :(得分:5)
{this.getFields().map((field, i) => {
<div key={i} className={field.classes}>
{checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)}
<div className="minilabel"></div>
</div>
})}
您的代码不会返回任何内容,因为您在函数语法中使用了花括号。 <或者
{this.getFields().map((field, i) =>
<div key={i} className={field.classes}>
{checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)}
<div className="minilabel"></div>
</div>
)}
或
{this.getFields().map((field, i) => {
return (
<div key={i} className={field.classes}>
{checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)}
<div className="minilabel"></div>
</div>
);
})}
对于干净的代码,我会将map函数保留在JSX标记之外:
render() {
let values = this.state.fieldValues;
const checkType = this.checkType.bind(this);
const fields = this.getFields().map((field, i) =>
<div key={i} className={field.classes}>
{checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)}
<div className="minilabel"></div>
</div>
);
return(
<div className="formwrapper thinshadow">
<h3>{this.props.header}</h3>
{fields}
<button className="btn btn-primary"
onClick={() => this.props.onClick(values)} >
Save
</button>
</div>
);
}