我正在尝试制作一个动态输入表单,通过单击该按钮将生成新的描述输入字段行。我在状态内使用一个数组来跟踪它们:
state = {
descriptions: [
{
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Description'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
}]
}
因此,在我的render方法中,我使用了这样的变量来填充表单:
let descriptionsForm = (
<form>
{this.state.descriptions.map((description, index) => (
<Input
key={index}
elementType={description.elementType}
elemenyConfig={description.elementConfig}
value={description.value}
invalid={!description.valid}
shouldValidate={description.validation}
touched={description.touched}
changed={(event) => this.descriptionInputChangedHandler(event, index)}
/>
))}
</form>
<Button btnType={"Success"} clicked={this.pushDescription}>Add Description</Button>
)
这是pushDescription函数:
pushDescription = () => {
var d = {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Description'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
};
this.state.descriptions.push(d);
console.log(this.state.descriptions);
}
因此,当我单击“添加描述”按钮时,控制台会闪烁1秒钟的更新描述,其中包含2个元素,但很快会刷新为原始状态。该网站完全不变。
我在做什么错?任何帮助表示赞赏。
编辑:修复了表单标签问题后,好像我在输入表单中键入内容时,新创建的表单确实出现了。为什么当我立即单击按钮时它们没有更新?
感谢大家的回答,有效的更新处理程序如下所示:
pushDescription = () => {
var d = {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Description'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
};
let newDescriptions = [
...this.state.descriptions,
d
]
// this.state.descriptions.push(d);
this.setState({ descriptions: newDescriptions})
console.log(this.state.descriptions);
}
答案 0 :(得分:2)
似乎您的组件没有重新渲染。尝试
this.setState({ description: this.state.description.push(d) });
仅在以下情况下,这将使您的组件重新呈现为组件重新渲染:
答案 1 :(得分:1)
答案 2 :(得分:0)
尝试更新您的渲染方法
let descriptionsForm = (
<form>
{this.state.descriptions.map((description, index) => (
<Input
key={index}
elementType={description.elementType}
elemenyConfig={description.elementConfig}
value={description.value}
invalid={!description.valid}
shouldValidate={description.validation}
touched={description.touched}
onChange={(event) => this.descriptionInputChangedHandler(event, index)}
/>
))}
<Button btnType={"Success"} onClick={this.pushDescription}>Add Description</Button>
</form>
)
使用'onClick'而不是'clicked',并且 “ onChange”而不是“ changed”
希望它会有所帮助:)