Reactクローンコンポーネント:React.cloneElement()

2644 ワード

reactはクローンAPIを提供します.
React.cloneElement(
  element,
  [props],
  [...children]
)

公式定義:
Clone and return a new React element using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

次に、Reactを介してdemoを実現する.cloneElementは、stateおよびfunctionをサブコンポーネントに渡します.コードは次のとおりです.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MyContainer extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 1
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.state.count++;
        this.setState({
            count: this.state.count++
        })
        console.log(this.state)
    }

    render() {
        const childrenWithProps = React.Children.map(this.props.children, child => React.cloneElement(child, 
            {
                parentState: this.state.count,
                handleClick: this.handleClick
            }
        ));
        return (
            
: { childrenWithProps }
) } } class MySub extends Component { constructor(props) { super(props) this.state = { flag: false } } render() { return (
:{this.props.subInfo}
count : { this.props.parentState }
this.props.handleClick() } style={{display:"inline-block",padding: "3px 5px", color:"#ffffff", background: "green", borderRadius: "3px", cursor: "pointer"}} >click me
) } } ReactDOM.render ( ( ) , document.getElementById('content'))



    
    react drag components example...