![](/img/trans.png)
[英]Warning: A component is changing an uncontrolled input of type undefined to be controlled
[英]changing an uncontrolled input of type undefined to be controlled
我正在從官方文檔中學習ReactJS,並試圖編寫一個溫度計算器來計算在給定溫度下水是否會沸騰。 ( 更多信息 )盡管以下代碼按預期運行,但我得到警告
“ proxyConsole.js:56警告:TemperatureInput正在將類型為undefined的不受控制的輸入更改為受控。輸入元素不應從不受控制的狀態切換為受控的狀態”
誰能告訴我我錯了嗎? 非常感謝!
function BoilingVerdict(props) {
if (props.temperature >= 100) {
return <p>The water would boil</p>
} else {
return <p>The water would not boil</p>
}
}
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
return (
<fieldset>
<legend>Please enter temperature in {Calculate.scaleNames[this.props.scale]}</legend>
<input value={temperature} onChange={this.handleChange} />
</fieldset>
)
}
}
class Calculate extends React.Component {
constructor(props) {
super(props);
this.state = {
temperature: "",
scale: "c"
}
this.handleCelciusChange = this.handleCelciusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
}
static scaleNames = {
c: "Celcius",
f: "Fahrenheit"
}
static toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
static toFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
static tryConvert(temp, convert) {
const input = parseFloat(temp);
if (Number.isNaN(input)) { return; }
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
handleCelciusChange(temperature) {
this.setState({
scale: 'c',
temperature: temperature
})
}
handleFahrenheitChange(temperature) {
this.setState({
scale: 'f',
temperature: temperature
})
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const Celcius = scale === 'f' ? Calculate.tryConvert(temperature, Calculate.toCelsius) : temperature;
const Fahrenheit = scale === "c" ? Calculate.tryConvert(temperature, Calculate.toFahrenheit) : temperature;
return (
<div>
<TemperatureInput scale="c" onTemperatureChange={this.handleCelciusChange} temperature={Celcius} />
<TemperatureInput scale="f" onTemperatureChange={this.handleFahrenheitChange} temperature={Fahrenheit} />
<BoilingVerdict temperature={Celcius} />
</div>
)
}
}
ReactDOM.render(<Calculate />, document.getElementById('root'))
我認為問題出在tryConvert
函數上。
在初始狀態下, temperature
以空字符串( ""
)初始化。 因此,當將此空字符串提供給tryConvert
方法的parseFloat
時,它將轉換為NaN
。 然后,您處於Number.isNaN
條件,並且您的方法返回undefined
。
最后,當您在字段中輸入值時,該值將變為實數浮點,並且輸入從uncontrolled
值( undefined
值)切換為controlled
(有關受控制和不受控制的狀態https:// facebook,請參閱此文檔。 github.io/react/docs/forms.html#受控組件 )
您可以通過多種方式來修復代碼。 您可以修復tryConvert
以始終返回有效數字(即使用戶輸入隨機字符串),也可以修復狀態的temperature
屬性的初始值。
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.