好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用React组件编写温度显示器

本文实例为大家分享了React组件编写温度显示器的具体代码,供大家参考,具体内容如下

这是模拟了一下温度显示器的效果,先看效果:

先在页面中引入React等;

import React from "react";
import ReactDOM from "react-dom";
import "./index.css"; // 页面的样式文件

开发过程是这样的:

首先定义一个BoillingVerdict组件,用来显示温度显示器的(样式先不写,在后面一起上代码)(温度显示器上的数字不是温度;),

// 显示温度计算器文字的函数组件(最高300摄氏度)
function BoillingVerdict(props) {
? return (
? ? <div className="outer">
? ? ? <div className="inner" style={{ height: props.height + "%", background: props.bg, }} >
? ? ? ? {props.height}
? ? ? </div>
? ? </div>
? );
}

然后,创建一个名为 Calculator 的组件,用于渲染  '控制温度的输入框' 和 温度显示器组件,

class Calculator extends React.Component {
? // 构造函数,可以用于初始化state
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? temperature: 0, // 温度
? ? ? tempHeight: 0, // 温度显示器背景色高度
? ? ? bg: "#fff", // 温度显示器颜色
? ? };
? ? // 为tempChange方法绑定this,否则该方法中拿不到this
? ? this.tempChange = this.tempChange.bind(this);
? }
? tempChange(e) {?
? ?// 判断温度值大小来设置颜色
? ? var colors =
? ? ? Number(e.target.value) > 90 ? "#0F1CED" : Number(e.target.value) > 80 ? "#D5D70B" :
? ? ? Number(e.target.value) > 70 ? "#0BD737" : Number(e.target.value) > 60 ? "#0BD7CA" :
? ? ? Number(e.target.value) > 50 ? "#ED194B" : Number(e.target.value) > 40 ? "#AE1FD2" :
? ? ? Number(e.target.value) > 30 ? "skyblue" : Number(e.target.value) > 20 ? "blue" :
? ? ? Number(e.target.value) > 10 ? "orange" : "#671552";
? ? var height = (Number(e.target.value) / 3).toFixed(2);
? ? this.setState({
? ? ? temperature: e.target.value,
? ? ? tempHeight: height,
? ? ? bg: colors,
? ? });
? }
? render() {
? ? return (
? ? ? <fieldset>
? ? ? ? <legend> 温度: </legend>
? ? ? ? <input value={this.state.temperature} onChange={this.tempChange} type="number" > </input>
? ? ? ? <BoillingVerdict height={this.state.tempHeight} bg={this.state.bg}></BoillingVerdict>
? ? ? </fieldset>
? ? );
? }
}

然后渲染:

ReactDOM.render(<Calculator></Calculator>,document.getElementById("root12"));

index.css

.outer{
? width:80px;
? height:300px;
? border:1px solid black;
? border-radius: 20px;
? overflow: hidden;
? background:#fff;
? margin-top:10px;
? position:relative;
? text-align: center;
}
.inner{
? position:absolute;
? bottom:0;height:200px;
? background:#fff;
? width:100%;
? background:blue;
? text-align: center;
? transition: all 1s;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于使用React组件编写温度显示器的详细内容...

  阅读:36次