React 父子组件互相交互

script分为三个部分:

  1. ReactDOM.render
  2. Father 构造父组件
  3. Sub 构造子组件

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>react 组件通信title>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js">script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js">script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js">script>
head>
<body>
    <div id="example">div>
    <script type="text/babel">
        class Father extends React.Component{
            constructor(){
                super()
                this.state = {
                    style:{color:'red'},
                    html:'hello',
                    sonText:'你好',
                }
            }

            changeSon(args){
                let str = args?'你好儿子':'hello son'
                this.setState({
                    sonText:str
                })
            }

            render(){
                const fatherFn = (color)=>{
                    this.setState({
                        style:{color:color},
                    })
                    console.log('fatherFn',this.state.style)
                }

                return (
                    <div>
                        <h1 style={this.state.style}>{this.state.html}-father-{this.state.style.color}</h1>
                        <button onClick={()=>{this.changeSon(1)}}>父亲</button>
                        <button onClick={()=>{this.changeSon(0)}}>father</button>
                        <Sub say={this.state.sonText} fatherEvent={fatherFn.bind(this)}/>
                    </div>
                )
            }
        }

        class Sub extends React.Component{
            subFn(color){
                return ()=>{
                    console.log('fn Sub')
                    this.props.fatherEvent(color);
                }
            }

            render(){
                return (
                    <div>
                        <h3>Sub</h3>
                        <h3>{this.props.say}</h3>
                        <button onClick={this.subFn('red')}>儿子红</button>
                        <button onClick={this.subFn('blue')}>儿子蓝</button>
                        <button onClick={this.subFn('green')}>儿子绿</button>
                        <button onClick={this.subFn('black')}>son</button>
                    </div>
                )
            }
        }

        ReactDOM.render(
            <div>
                <Father />
            </div>,
            document.getElementById("example")
        )
    script>
body>
html>

你可能感兴趣的:(js,react)