一.父到子传值
props
可以接收 数字,字符串,布尔,数组,对象,函数,jsx
- 子组件通过
props
接收父组件的值
代码实现
父组件
import React from "react"
import One from "../../components/One"
export default () => {
const getMes = () => {
console.log("我是父组件的函数");
}
return (
<div>
<h1>home</h1>
<hr />
<One msg={"我是父组件的值"} getMes={getMes}/>
</div>
)
}
子组件
import React from "react";
export default ({msg,getMes})=>{
return (
<div>
<h1>我是子组件A</h1>
<div>
<div>接收父组件的值:{msg}</div>
<button onClick={getMes}>触发父组件函数</button>
</div>
</div>
)
}
页面展示
二.子到父传值
- 子组件调用父组件传递过来的函数,并且把想要传递的数据当成函数的实参
代码实现
子组件
export default ({ childrenClick }) => {
return (
<div>
<h1>我是子组件A</h1>
<div>
<button onClick={() => childrenClick("我是子组件中的数据")}>触发子组件函数</button>
</div>
</div>
)
}
父组件
import One from "../../components/One"
export default () => {
const getSon = (val) => {
console.log("父页面",val);
}
return (
<div>
<h1>home</h1>
<hr />
<One childrenClick={(val) => getSon(val)} />
</div>
)
}
页面展示
三.兄弟传值
- 同页面之间兄弟组件传值
- 把子组件A中的数据传递给子组件B
- 先把A组件的数据子传父给父组件,在通过父传子给B组件
代码实现
父组件
import React,{useState} from "react"
import One from "../../components/One"
import Two from "../../components/Two"
export default () => {
const [num, setNum] = useState(0);
return (
<div>
<h1>home</h1>
<hr />
<One childrenClick={(val) => setNum(val)} />
<hr />
<Two num={num} />
</div>
)
}
组件A
import React,{useState} from "react";
export default ({ childrenClick }) => {
const [count, setCount] = useState(0);
const brother = () => {
setCount(count + 1)
childrenClick(count + 1)
}
return (
<div>
<h1>我是子组件A</h1>
<div>
<button onClick={() => brother()}>传值B组件函数:{count}</button>
</div>
</div>
)
}
组件B
export default ({ num }) => {
return (
<div>
<h1>我是子组件B</h1>
<div>
<div>接收A组件的值:{num}</div>
</div>
</div>
)
}
页面展示