react 子传父

 

 

//父组件
        class Parent extends React.Component{
            constructor(){
                super()
                this.state = {
                    num : ""
                }
            }
            changeNum=(e)=>{
                this.setState({
                    num: e.target.value
                })
            }
            render(porps){
                return (
                    <div>
               {/*展示的数据*/}
                        {this.state.num}
                      {/*子组件的事件名称changeInp*/}
                        <Childen changeInp={this.changeNum}></Childen>
                    </div>
                )
            }

        }
        
        ReactDOM.render(
            <Parent></Parent>,
            document.getElementById("root")
        );

 

 

//子组件
        class Childen extends React.Component {
            render(porps) {
                return (
                    <div>
                        {/*直接利用props触发事件*/} <input onInput={this.props.changeInp} /> </div> ) } }

 

//子   性能比前者要高
        class Childen extends React.Component{
            changeInpp = (e) => {
          //这里需从子组件获取event对象 并作为形参传过去
this.props.changName(e.target.value) } render(){ return( <p> <input type="text" onInput={this.changeInpp}/> </p> ) } }
//父类只需要接收数据并赋值就可以了
       changeInp = (val) =>{
                this.setState({
                    name: val
                })
            }
 
posted @ 2019-12-27 16:33  casf  阅读(403)  评论(0编辑  收藏  举报