学习React第四天

props和父子组件传值

import React from "react";
// 引入 MySon 子组件
import MySon from "./MySon";

// 父组件
class App extends React.PureComponent {
  state = {
    mes:'你好呀'
  };
  render() {
    return (
      <div className="App">
        <p>父组件</p>
        {/* 可以直接这样传值 a="" 也可以这样 msg={} 传值 */}
        {/* 在react props不传才显示默认值 */}
        {/* 在react props不传才显示默认值 */}
        {/* 类似于vue作用域插槽 scopeslot={(scope) => { return <div>{scope }</div> }}
            在父组件scope接收子组件传过来的数据 进行展示
         */}
        
        <MySon a={<span>类似于vue中的具名插槽</span>} scopeslot={(scope) => { return <div>{scope }</div> }} msg={this.state.msg}>
          <div>类似于vue中的插槽</div>  
        </MySon>
      </div>
    );
  }
}

export default App;
import React from "react";
// MySon 子组件
class MySon extends React.PureComponent {
  state = {
    somMsg: "这是作用域插槽",
  };
  render() {
    // 直接打印this.props可以拿到父组件所有传过来的数据
    console.log(this.props);
    return (
      <div className="MySon">
        <p>
          {/* this.props.msg 可以直接展示父组件传过来的值 */}
          子组件:{this.props.msg}
        </p>
         {/* 展示 父组件过来的html元素 类似于vue中的插槽 */}
        {this.props.children}
        <p>类似于vue具名插槽: {this.props.a}</p>
         {/* 类似于vue作用域插槽 调用父组件的方法 把子组件的数据传过去*/}
        {this.props.scopeslot(this.state.somMsg) }
      </div>
    );
  }
}
// 设置类型
MySon.propTypes = {
  msg: function (props) {
    // 类型验证 不是一个字符串类型,就会抛出一个错误
    if (typeof props.msg !== "string") {    
      throw new Error("msg must be a string");
    }
  },
  ...其他类型验证
};
// 默认值 在react props不传才显示默认值
MySon.defaultProps = {
  msg: "i am msg default",
  ...其他属性默认值
};

export default MySon;

验证方法库 proptypes 继承了很多验证方法

 安装命令 `npm install proptypes --save`
//在MySon子组件 引入proptypes验证库
import proptypes from "proptypes" 

// 使用proptypes设置类型
MySon.propTypes = {
  msg: proptypes.string
};

父传子 

  {/* 父传子 msg={<span>内容</span>} msg="" */}
  <MySon msg={this.state.msg} content={<span>内容</span>}>
    <div>传给子组件内容</div>
  </MySon>

  //子组件接收
  <div className="MySon">
        {this.props.msg}
        {this.props.content}
        {this.props.children}
  </div>

子传父 

//子组件
 <div className="MySon">
     {this.props.msg}
     <button onClick={() => {
       this.props.changeMsg("子组件传给父组件的内容")
     }}>修改</button>
  </div>


//父组件
 changeMsg(sonmsg) {
    console.log('子组件传过来的值', sonmsg);
    //会出现this 指向问题
    this.setState({
      msg: item
    })
  }
//在这里添加 .bind()可以解决this指向问题
<MySon msg={this.state.msg} changeMsg={this.changeMsg.bind(this)}></MySon>

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值