React 深入 JSX(10)

JSX

  • JSX 其实是 React.createElelment 函数调用的语法糖
  • JSX 会将代码编译成 React.createElelment 调用形式
React.createElement(
  "div",
  {
    className: "box",
  },
  "boxbox"
)
  • JSX 中使用点语法
const colorSystem = {
  primary: "blue",
  success: "green",
  danger: "red",
};
const MyUI = {
  Button: class extends React.Component {
    render() {
      const { type, children } = this.props;
      return (
        <button style={{ color: "#fff", backgroundColor: colorSystem[type] }}>
          {children}
        </button>
      );
    }
  },
};

class App extends React.Component {
  render() {
    return (
      <div>
        {/* 点语法 */}
        <MyUI.Button type="success" children="click!"></MyUI.Button>
      </div>
    );
  }
}

书写规范

  • 小写字母开头代表 HTML 的内置组件 (<div>/<h1>/<span>/<p>),将转换为 React.createElelment 第一个参数
  • 大写字母开头代表自定义组件 <MyButton />,编译为 React.createElelment(<MyButton />)

运行时选择 React 组件

class LoginBtnGroup extends React.Component {
  render() {
    return (
      <div>
        <button>登录</button>
        <button>注册</button>
      </div>
    );
  }
}

class WelcomeInfo extends React.Component {
  render() {
    return (
      <div>
        <button>欢迎登录</button>
      </div>
    );
  }
}

class Header extends React.Component {
  static components = {
    login: LoginBtnGroup,
    welcome: WelcomeInfo,
  };
  render() {
    const HeaderUser = Header.components[this.props.type];

    return <HeaderUser />;
  }
}

class App extends React.Component {
  state = {
    isLogin: true,
  };
  render() {
    return (
      <div>
        <Header type={this.state.isLogin ? "welcome" : "login"} />
      </div>
    );
  }
}

JSX 的 props

class Content extends React.Component {
  render() {
    return <div>{this.props.content}</div>;
  }
}
class App extends React.Component {
  state = {
    isLogin: true,
  };
  render() {
    return (
      <div>
        {/* js表达式方式传入 props, HTML 实体字符会被转义成普通字符 */}
        {/* &lt;asdfa&gt; */}
        <Content content={"&lt;asdfa&gt;"} />

        {/* 字符串字面量传入props方式,不会对HTML实体转义 */}
        {/* <asdfa> */}
        <Content content="&lt;asdfa&gt;" />
        {/* <asdfa> */}
        <Content content="<asdfa>" />

        <div
          dangerouslySetInnerHTML={{
            __html: "<code>reacr</code> <br/> First &nbsp;&nbsp;&nbsp; Second",
          }}
        ></div>
      </div>
    );
  }
}
  • JSX props bool 的表达
class MyTitle extends React.Component {
  render() {
    console.log(this.props.isShow);
    const { isShow, children } = this.props;

    return (
      <div style={{ display: isShow ? "block" : "none" }}>
        jsx 中 props 的 bool 值: {children}
      </div>
    );
  }
}
class App extends React.Component {
  render() {
    return (
      <div>
        {/* 只是字符串,不代表 bool */}
        <MyTitle isShow="false" children="字符串类型" />
        {/* 布尔类型 */}
        <MyTitle isShow={true} children="布尔类型"/>
        {/* 不赋值属性,默认为 true */}
        {/* 不推荐这么做,语义不好,类似ES6的对象省略属性值  {isShow} ==> {isShow: isShow}  */}
        <MyTitle isShow children="布尔默认值"/>
      </div>
    );
  }
}
  • 属性展开操作
class MyTitle extends React.Component {
  render() {
    console.log(this.props);
    const { isShow, title, children } = this.props;

    return <div style={{ display: isShow ? "block" : "none" }}>{title}--{children}</div>;
  }
}

class App extends React.Component {
  render() {
    // 把不需要的提出来,子组件中需要的放到剩余参数
    const { content, ...others } = this.props;

    return (
      <div>
        {/* 默认展开 */}
        <MyTitle {...others} />
      </div>
    );
  }
}

ReactDOM.render(
  <App
    isShow={true}
    title="This is a Title"
    content="This is Contentsssss"
  >
    {/* 这里默认是 children,会自动加到 props 中 */}
    This is Childrenssss
  </App>,
  document.querySelector("#app")
);
  • 字符串字面量
  1. 会自动去掉首尾空格换行
  2. 字符串之间的多个空格压缩为一个空格(使用 &nbsp; 实现多个空格 )
  3. 字符串之间的换行压缩为一个空格(使用 <br/> 实现换行)
class MyTitle extends React.Component {
  render() {
    return <div>{this.props.children}</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <MyTitle>   This is a &lt;Title&gt;    </MyTitle>
        <MyTitle>{"This is a &lt;Title&gt;"}</MyTitle>
        <MyTitle>{"This is a <Title>"}</MyTitle>
      </div>
    );
  }
}

JSX 作为 JSX 的子元素

class MyList extends React.Component {
  render() {
    return (
      <div className={this.props.listClassName}>
        <h1>{this.props.title}</h1>
        <ul>{this.props.children}</ul>
      </div>
    );
  }
}

class ListItem extends React.Component {
  render() {
    return <li>{this.props.children}</li>;
  }
}

class ListItems extends React.Component {
  render() {
    // 返回多个jsx
    // return [
    //   <li>This is content 1</li>,
    //   <li>This is content 2</li>,
    //   <li>This is content 3</li>,
    // ];

    return this.props.listData.map((item, index) => (
      <li>
        {index}-{item}
      </li>
    ));
  }
}

class App extends React.Component {
  state = {
    listData: ["This is content 1", "This is content 2", "This is content 3"],
  };
  render() {
    return (
      <div>
        <MyList listClassName="my-list-wrap" title="MyList">
          {this.state.listData.map((item, index) => (
            <ListItem key={index}>
              {item}-{Date.now()}
            </ListItem>
          ))}
          <ListItems listData={this.state.listData} />
        </MyList>
      </div>
    );
  }
}

null/undefined/bool 作为 JSX 的子元素

这些元素会被忽略,不渲染(空标签)

class App extends React.Component {
  state = {
    data: [],
  };
  render() {
    return (
      <div>
        {/* - - */}
        <div>- {true} -</div>
        <div>- {false} -</div>
        <div>- {undefined} -</div>
        <div>- {null} -</div>
        <div>- {String(null)} -</div>
        <div>- {this.state.data.length ? "有数据" : "无数据"} -</div>
        {/* 0 */}
        <div>- {this.state.data.length && "有数据"} -</div>
        {/* 空 */}
        <div>- {this.state.data.length > 0 && "有数据"} -</div>
      </div>
    );
  }
}

props.children 是函数

JSXprops.childrenprops 本身是有一致性的特性,props.children 就可以传递任何类型的子元素

简单案例

class Repeat extends React.Component{
  render(){
    const jsxArr = []
    for (let i = 0; i < this.props.num; i++) {
      jsxArr.push(this.props.children(i))
    }
    return jsxArr
  }
}
class App extends React.Component {
  state = {
    data: [],
  };
  render() {
    return <div>
      <Repeat num={10}>
        {
          index => <p key={index}>This is item {index}</p>
        }
      </Repeat>
    </div>;
  }
}
function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([
        {
          id: 1,
          name: "zs",
          grade: 4,
        },
        {
          id: 2,
          name: "pdd",
          grade: 7,
        },
        {
          id: 3,
          name: "tui",
          grade: 8,
        },
      ]);
    }, 1500);
  });
}
const Http = {
  Get: class extends React.Component {
    state = {
      students: [],
      component: this.props.loading || "loading",
    };
    async componentDidMount() {
      const res = await getData();
      this.setState({
        students: res,
        component: this.props.children(res)
      });
    }
    render() {
      return this.state.component;
    }
  },
};

class Table extends React.Component {
  render() {
    return (
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年级</th>
          </tr>
        </thead>
        <tbody>
          <Http.Get
            url="xxx"
            loading={
              <tr>
                <td colSpan={3}>正在加载中...</td>
              </tr>
            }
          >
            {(data) => {
              return data.map((item) => (
                <tr key={item.id}>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.grade}</td>
                </tr>
              ));
            }}
          </Http.Get>
        </tbody>
      </table>
    );
  }
}

class App extends React.Component {
  state = {
    data: [],
  };
  render() {
    return (
      <div>
        <Table />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"));
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容