我处于那种状态:
state = {
val: '',
input: [{
id: uuid.v4(),
questionLabel: 'Question',
text: '',
typeLabel: 'Type',
conditionLabel: 'Condition',
types: [
{value: '', name: ''},
{value: 'Text', name: 'Text'},
{value: 'Number', name: 'Number'},
{value: 'Yes / No', name: 'Yes / No'}
],
subInput: []
}],
}
那个功能:
textChangeHandler = event => {
const text = this.state.input.map(currency => {
const test = currency.text = event.target.value;
return {...currency, text: test}
});
this.setState({text})
}
我想更改输入的状态,属性:text
但是,如果我输入文字,那是行不通的,我不能输入文字,状态也不会改变。我如何解决此功能?
答案 0 :(得分:0)
这是因为您正在直接改变状态。并且不允许在react应用程序中更改状态。您可以在此处执行以下操作:
textChangeHandler = (event, inputIndex) => {
const test = [...this.state.input] // first, clone the input state
// now, you can update the text
test[inputIndex].text = event.target.value
this.setState({
input: test // test is now whole updated input array
})
}
通知:您需要在处理程序中传递索引,以便它知道要更改的索引。
如果您喜欢以下情况:
textChangeHandler = event => {
const test = [...this.state.input]
test.forEach(t => t.text = event.target.value)
// but wait, event.target.value?
// this will change all the input with the same value
this.setState({
input: test
})
}
因此,最好使用索引来更新值。