一先说说软件和代码的关系,具体点先说表示层和代码的关系吧。
先说一个过程吧。
创建控件=>设置属性=>页面表示出来。
这是一个传统的过程,传统的代码应该类似于这样的。
using System;
using System.Windows.Forms;
namespace 创建简单桌面
{
class Program : System.Windows.Forms.Form
{
public Program()
{
lb1 = new Label();
lb1.Text = "我是控件";
this.Controls.Add(lb1);
}
private Label lb1;
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("创建窗体");
Application.Run(new Program());
Console.ReadLine();
}
}
}
单是后来,在xml盛行的时代, ui的代码编程了这样。(这里是有html得到的启发,将ui由代码中分离出来)
<Page x:Class="WPF窗口.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPF窗口"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Page1">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="113,61,0,0" TextWrapping="Wrap" Text="我是控件" VerticalAlignment="Top" Width="120"/>
</Grid>
</Page>
我要说的是:任何ui背后的本质都是代码,html也不例外,只不过,由于html一开始就给人一种用像xml表示的方式出现的,说以给人感觉,浏览器表示的内容视乎是因为html而非代码。其实浏览器表示出来的过程是这样的,html=>代码=>编译成页面的样子。说以本质上 “JSX”,是自定义的一层代码解释方式而已。他吧html向代码解析的过程替换了,JSX=>代码=>编译。
浏览器的表示背后的本质和其他ui的表示背后的本质一样都是代码。如下举例。
代码
<!DOCTYPE html>
<html>
<body>
<div id="div1">
</div>
<script>
var para=document.createElement("div");
var node = document.createElement("input");
node.value = "ddd";
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
这里完全用代码生成了一个表单,说以JSX最终会翻译成代码,执行,说以JSX也就没有什么神秘之处了,只不过能解析成浏览器真正识别的代码。
html任何控件的本质都是代码,这一切就都不神秘了。