Test6_ParentChild.cshtml

125 lines | 2.828 kB Blame History Raw Download

@{
    ViewBag.Title = "Test6_ParentChild";
}

<h2>Test6_ParentChild</h2>
<div id="app"> </div>


<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>

<script type="text/babel">

class ChildComponent extends React.Component{
    
    constructor(props){
        super(props);

        this.state = {color: "red"};

        this.OnClick = this.OnClick.bind(this);
        this.SetButtonState = this.SetButtonState.bind(this);

        this.props.OnCreate(this);
    }

    componentWillUnmount(){
        this.props.OnDestroy(this);
    }

    
    OnClick(event){
        this.props.OnClick(this, event);
    }    

    SetButtonState(state){
        let color = "";
        
        if (state === 1)
            color = "green";
        else
            color = "red";

        this.setState({color: color});
    }

    render(){
        return (<p>
            <button onClick={this.OnClick} style={{backgroundColor: this.state.color}}>elem id: {this.props.id}</button>
        </p>
        );
    }    
}

class ParentComponent extends React.Component{
    
    constructor(props){
        super(props);

        this.state = { Text: "NoText", data: [{id: 10}, {id: 11}, {id: 12}]};
        this.childs = [];

        this.OnChildClick = this.OnChildClick.bind(this);     
        this.OnChildCreate = this.OnChildCreate.bind(this);
        this.OnChildDestroy = this.OnChildDestroy.bind(this);
    }

    OnChildCreate(child){
        this.childs.push(child);
    }
    OnChildDestroy(child){
        delete this.state.childs[child.id];
    }

    OnChildClick(child, event){
        console.log(child);
        console.log(event);

        var text = "Click to " + child.props.id;

        this.childs.map(function(elem)
        {
            elem.SetButtonState(0);
        });
        child.SetButtonState(1);

        this.setState({Text: text});
    }

    render(){
        return(
        <div>
        <p>{this.state.Text}</p>
            
            <table>
                <tr>
                    <th>row numb</th>
                    <th></th>
                </tr>

            {
                this.state.data.map(function(elem, index, array){
                    return (
                    <tr>
                        <td>{index}</td>
                        <td><ChildComponent id={elem.id} OnClick={this.OnChildClick} OnCreate={this.OnChildCreate} OnDestroy={this.OnChildDestroy}  /></td>
                    </tr>
                    )
                }.bind(this))
            }
            </table>

        </div>
        );
    }

}
 
ReactDOM.render(
    <ParentComponent />,
    document.getElementById("app")
)
</script>