React中如何根据温度值动态设置段落背景色及语法错误解决
报错原因
这是React类组件的语法错误:你在类组件的主体内部直接用const声明getBackground函数,类组件内部定义成员函数/变量不能用const、let这类普通变量声明关键字,只有类方法、类属性的写法才合法。你旁边的renderForecast1用的是类属性箭头函数的写法符合规范,但getBackground前面多了const就违反了类组件的语法规则。
解决方案
两种常见写法任选其一即可:
方案1:把getBackground改成类属性(和现有写法统一)
删掉getBackground前面的const,调用时加上this.前缀即可,修改后的代码如下:
// 去掉前面的const,改成类属性写法 getBackground = (temperature) => { if(temperature > 30) return "red" if(temperature > 20) return "orange" if(temperature > 10) return "yellow" return "transparent" } renderForecast1 = () => { if (this.state && this.state.list) { const list = this.state.list[0]; return ( // 调用时加this.前缀 <p style={{ backgroundColor: this.getBackground(list.main.temp) }}> Date: {list.dt_txt}h <br /> Temperature: {list.main.temp} °C <br /> Chance of precipitation: {list.pop} mm <br /> Wind Speed: {Math.round(list.wind.speed, 1) * 3.6} km/h <br /> Pressure: {list.main.pressure} hPa <br /> Humidity: {list.main.humidity} % </p> ); } };
方案2:把getBackground挪到类组件外部
如果这个工具函数不需要访问类的其他属性,你可以直接把它放到整个class定义的外部,就可以保留const声明:
// 放在class App extends Component {} 定义的外面 const getBackground = (temperature) => { if(temperature > 30) return "red" if(temperature > 20) return "orange" if(temperature > 10) return "yellow" return "transparent" } class App extends Component { // 你的其他类代码,包括state定义、生命周期、renderForecast1等 renderForecast1 = () => { if (this.state && this.state.list) { const list = this.state.list[0]; return ( // 调用不需要加this,直接用函数名即可 <p style={{ backgroundColor: getBackground(list.main.temp) }}> Date: {list.dt_txt}h <br /> Temperature: {list.main.temp} °C <br /> Chance of precipitation: {list.pop} mm <br /> Wind Speed: {Math.round(list.wind.speed, 1) * 3.6} km/h <br /> Pressure: {list.main.pressure} hPa <br /> Humidity: {list.main.humidity} % </p> ); } }; }
两种方案修改完成后即可解决语法报错,温度对应的动态背景色逻辑也会正常生效。
内容的提问来源于stack exchange,提问作者Blagovest Pizhev
相关产品推荐
相关产品推荐

