问题描述
我一直在想是否有一种方法可以将条件作为道具发送给需要一些条件渲染并迭代一组动态对象的子组件。
比方说,我希望有条件地渲染其中一个对象,因此请执行以下操作:
const Content = [{
object: "One",value: one,name: "object1"
},{
object: "Two",value: two,name: "object2",condition: object1.value === "One"
}]
因此,根据第一个对象的值(假设它是一个选择标签),我希望第二个对象被呈现。
然后我们有对象:
然后,在组件内部,我将迭代对象并有条件地呈现输入或选择。
有什么想法吗?预先感谢。
编辑:
这是组件
function FormCase ({ onSubmit,register,content }) {
return (
<Form id="form" onSubmit={onSubmit}>
<Row className="form-row">
{content.map((obj,idx) => {
return (
obj.conditional &&
<div className="form-group" key={idx}>
<label>{obj.name}</label>
<input className="form-control" value={obj.value} />
</div>
)
})}
</Row>
<Row className="submit-row">
<input type="submit" value="Create" />
</Row>
</Form>
)
}
解决方法
const content = [{
object: "One",value: one,name: "object1"
},{
object: "Two",value: two,name: "object2",condition: value => value === "One"
}]
// while rendering
const toRender = content.filter(item => !item.condition || item.condition("some value"));
// or filter function of your choice
然后只渲染过滤的项目。
编辑:
function FormCase ({ onSubmit,register,content }) {
return (
<Form id="form" onSubmit={onSubmit}>
<Row className="form-row">
{content.map((obj,idx) => {
if (idx > 0) { // don't check the condition for first
return (
obj.condition && obj.condition(content[idx-1].value) &&
<div className="form-group" key={idx}>
<label>{obj.name}</label>
<input className="form-control" value={obj.value} />
</div>
)
} else {
return (
<div className="form-group" key={idx}>
<label>{obj.name}</label>
<input className="form-control" value={obj.value} />
</div>
)
}
})}
</Row>
<Row className="submit-row">
<input type="submit" value="Create" />
</Row>
</Form>
)
}
因此,您只需在condition
数组中将函数作为content
传递即可。在渲染期间,您应该检查condition
,其中前一项值为函数的参数。
您应该调整逻辑-condition
对象中没有定义content
函数时该怎么办。