简体   繁体   中英

reactjs - Input defaultValue is set but not showing

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"
            />

在此处输入图像描述

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.

I agreed with the solution provided by @Daltron, but it can also be solved by putting the key prop binding with its value instead of adding random values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM