React组件传值

(1)父传子(使用useState)

父组件中:

import Child from "./Child"
const Father: React.FC = () => {
  const [count,setCount] = useState(0);
  return(
    <div>
      <h1>父组件点击了{count}次</h1>
      <button onClick = {() => setCount(count + 1)}>点击< /button>
      <hr />
      <Child msg = {count}>
    </div>
  )
}
erxport default Father

子组件中:

​interface childProps {
    msg: number;
}
const Child: React.FC<childProps> =(props) =>{
    const {msg} = props;
    return(
      <div>
        <h2>子组件接收了{msg}次</h2>
      </div>
    )
}
export deafult Child

(2)子传父

父组件中:

​import Child from "./Child"
const Father: React.FC =() ={
    const [count,setCount] = useState(0)
    return(
      <div>
          <h1> 父组件接收到的次数是{count}次</h1>
          <hr />
          <Child msg = {count} changeCount = {(code:number) => setCount(code)} / >、
      </div >
    )
}

子组件中:

​interface childProps {
    msg: number;
    changeCount: Function
}
const Child: React.FC =() =>{
    const { msg, changeCount } = props;
    return(
        <div>
          <h2> 子组件的点击次数是{msg}次</h2>
          <button onclick = {() => changeCount(msg+1)}> 点击</button>
        </div>
    )
}

(3)使用context传值

​
import Parent extends React.Component {
    value = {
        message: 'hello',
    };
    render() {
        return(
          <child> {this.value.message} </child>
        );
    }
}
class Child extends React.Component {
    render() {
        return(
          <div> {this.props.children}</div>
        )
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值