props传值
- 函数组件
相当于是变量提升,把参数定义在父组件,通过props传递给子组件
function Parent() {
let a = 1;
//父组件
return (
<div>
<Child a={a}></Child>
</div>
);
}
function Child(props: any) {
let { a } = props;
子组件
return <div>a的值为{a}</div>;
}
ref传值
import React, { useRef } from "react";
import Child from "./Child";
function Parent() {
const childRef: any = useRef();
return (
<div>
<Child childRef={childRef}></Child>
<div onClick={() => childRef?.current?.getAge()}>获取子组件的参数</div>
</div>
);
}
export default Parent;
子组件
import React, { useImperativeHandle } from "react";
function Child(props: any) {
let { childRef } = props;
useImperativeHandle(childRef, () => {
return {
// 返回值
person: {
name: "张三",
},
getAge() {
console.log(this.person, "this");
},
};
});
return <div></div>;
}
export default Child;
补充getAge值为对象的方法和箭头函数的区别
getAge() {
console.log(this, "this");可以拿到this,
},
getAge=() =>{
//不能拿到this,设置的其他值
},