reactjs - Input defaultValue is set but not showing

◇◆丶佛笑我妖孽 提交于 2019-12-11 13:26:17

问题


Noticed some weirdness that defaultValue is set for input, but sometimes it's not visible when page is refreshed. I have tried console.log then component re-renders multiple times as data is loaded, on the last re-render the component contains the required value, as you can see on screenshot, but it's not shown. Any idea why? Thank you

<input type="text" name={this.props.question.id}
                defaultValue={defaultValue}
                onChange={this.onSingleChange.bind({
                    selectAnswer: this.props.selectAnswer,
                    question: this.props.question,
                    form: this.props.fid
                })}
                className="form-control"
            />


回答1:


I had this same issue before. My solution was to add a key prop to my input that was a random number.

key={`${Math.floor((Math.random() * 1000))}-min`}

From what I have read, this has to do with defaultValue being set only on the initial render. The random number causes a re-render with the right default value.

Hope that helps.



来源:https://stackoverflow.com/questions/48991254/reactjs-input-defaultvalue-is-set-but-not-showing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!