React 深入 JSX(10)

2022-10-07  本文已影响0人  示十

JSX

React.createElement(
  "div",
  {
    className: "box",
  },
  "boxbox"
)
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>
    );
  }
}

书写规范

运行时选择 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>
    );
  }
}
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"));
上一篇下一篇

猜你喜欢

热点阅读