Sunshine168 / resume

My resume
3 stars 1 forks source link

React Top-Level Api eg1 #17

Open Sunshine168 opened 5 years ago

Sunshine168 commented 5 years ago

React.Children

map

import * as React from "react";

export default class ReactExample extends React.Component {
  render() {
    const { children, activeChildId } = this.props;
    return React.Children.map(children, child => {
      return child && child.props.id === activeChildId ? child : null;
    });
  }
}

eg:

import React from "react";
import ReactDOM from "react-dom";

import ChildrenExample from "./Children/index";

function App() {
  return (
      <ChildrenExample activeChildId="1">
        {[
          null,
          <div id="1" key="1">
            1
          </div>,
          <div id="2" key="2">
            1
          </div>
        ]}
      </ChildrenExample>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

toArray

import * as React from "react";

const Sort = props => {
  const children = React.Children.toArray(props.children);
  return children.sort().join();
};

export default Sort;

import React from "react";
import ReactDOM from "react-dom";

import Sort from "./Children/toArray";

function App() {
  return <Sort>{["c", "a", "b"]}</Sort>

}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

cloneElement

import * as React from "react";

export default class ActiveChildrenById extends React.PureComponent {
  render() {
    console.log({
      arrary:React.Children.toArray(this.props.children)
    })
    return React.Children.map(this.props.children, child =>
      !child ? (
        <div>nullElement</div>
      ) : child.props.id === this.props.activeId ? (
        React.cloneElement(child, {
          ...child.props,
          style: { color: "red" }
        })
      ) : (
        child
      )
    );
  }
}
import React from "react";
import ReactDOM from "react-dom";

import ActiveChildrenById from "./cloneElement/";

import "./styles.css";

function App() {
  const arr = [
    null,
    <div id="1" key="1">
      1
    </div>,
    <div id="2" key="2">
      2
    </div>
  ];
  return (
    <div className="App">
      <ActiveChildrenById activeId="1">{arr}</ActiveChildrenById>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesanbox