react Class组件的传参

408 阅读1分钟

父传子:

1:通过父组件中子组件标签的自定义属性传值:

<Child xxx={this.fn} />

2:在子组件中用接收标签传递过来的值

{this.props.xxx}

子传父:

1:通过父组件中子组件标签,自定义属性传递一个函数

 <Child tit={this.fn} />

2:在class类子组件的componentDidMount(挂载后),调用这个函数,并将子组件的数据通过函数的形参传给父组件

componentDidMount(){            this.props.tit(this.state.xxx);        }

3:在父组件的函数中接受子组件传过来的数据并设置state中的数据值

fn=(v)=>{            this.setState({                a:v            })        }

附上完整代码:

<body>    <div id="app"></div></body>

<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script><script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script><script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script><script src="https://unpkg.com/@babel/standalone/babel.min.js"></script><script type="text/babel">    class Child extends React.Component{        constructor(){            super();            this.state={                a:'我是子组件数据'            }        }        componentDidMount(){            this.props.tit(this.state.a);        }        render(){            return (                <div>                    <h2>我是子组件</h2>                </div>            )        }    }    class Com extends React.Component{        constructor(){            super();            this.state={                a:'我是父组件数组'            }        }        fn=(v)=>{            this.setState({                a:v            })        }        render(){            return (                <div>                    <h1>我是父组件----{this.state.a}</h1>                    <Child tit={this.fn} />                </div>            )        }    }    ReactDOM.render(<Com/>,document.getElementById('app'));