简体   繁体   English

reactjs - 输入默认值已设置但未显示

[英]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.注意到为输入设置了 defaultValue 的一些奇怪之处,但有时刷新页面时它不可见。 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.我已经尝试过 console.log,然后组件在加载数据时重新渲染多次,在最后一次重新渲染时,组件包含所需的值,如您在屏幕截图中所见,但未显示。 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道具。

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. 根据我的阅读,这与仅在初始呈现器上设置的defaultValue有关。 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.我同意@Daltron 提供的解决方案,但也可以通过将 key prop 绑定与其值而不是添加随机值来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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