React 父子组件传值,defaultProps,PropTypes

    xiaoxiao2023-11-10  156

    1.父子向子组件传值,可以传值,也可以传方法,也可以传整个组件this

    <Child title={this.state.title}/> // this.state.title是父级的state数据,传入属性的方式传值给子组件

    2.子组件获取值

    class Child extends Component{ constructor(props){ super(props) } render(){ return( <div>{this.props.title}</div> ) } } // this.props可以获取父级传过来的属性

    3.子组件向父组件传值,是通过父组件属性传过来的方法的参数进行传值

    //父组件 <Child title={this.state.title} callback={this.getChildMsg}/> getChildMsg=(msg)=>{ console.log(this) console.log(`子组件的数据${msg}`) } //getChildMsg是父组件的方法,传给子组件回调 //子组件 <button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button> //通过props获取传过来的方法,进行参数传值给父级

    4.父组件调用子组件的实例

    <Child ref="cd" title={this.state.title} callback={this.getChildMsg}/> // 通过ref进行获取 getChild=()=>{ console.log(this.refs.cd) //获取子组件的实例 this.refs[refName] console.log(this.refs.state) }

    5.设置组件的默认值

    class Child extends Component{ constructor(props){ super(props); console.log(this.props) this.state={ msg:"传入父级组件的数据" } } render(){ return( <div> <p>{this.props.title}</p> <p>{this.props.name}</p> <button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button> </div> ) } } Child.defaultProps={ title:"默认标题", name:"默认name" } // 直接设置defaultProps就行,属性没有赋值时候,就会获取默认值

    6.设置属性的类型

    import PropTypes from "prop-types" //引入模块 class Child extends Component{ constructor(props){ super(props); console.log(this.props) this.state={ msg:"传入父级组件的数据" } } render(){ return( <div> <p>{this.props.title}</p> <p>{this.props.name}</p> <button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button> </div> ) } } Child.defaultProps={ title:"默认标题", name:"默认name" } Child.propTypes={ title: PropTypes.string, //字符串 name: PropTypes.number //number类型 } //类似defaultProps的定义方式 //上面title是string类型,name是number类型,所以默认值name就会报错,因为默认值是string,不匹配

     

    最新回复(0)