在开发的过程中的时候,为了提高可读性或者复用性,我们会进行组件的拆分。
在引入子组件的时候,子组件的名字一定要大写,否则会报错(这是babel编译机制的问题)
具体案例:
父传子:
首先实现一个简单的父组件Home 向子组件Child 传递count的值,子组件通过props拿到此值并且渲染在页面上。
父组件:Home
import React from 'react'
import Child from './components/Child'
function Home() {
const [count, setCount] = React.useState(12345)
return (
<div>
<button onClick={()=> setCount(count+1)}></button>
<Child count={count} />
</div>
)
}
export default Home
子组件:Child
import React from "react";
function Child(props) {
const { count } = props;
return <div>获取到的值是:{count}</div>;
}
export default Child;
子传父:
首先,在子组件内部,修饰了父组件的值,从而完成子组件向父组件的通信
子组件:
import React, { useState } from "react";
function Child() {
const [count, setCount] = useState(666666)
const addCount = (val) => {
setCount(val);
};
return (
<div className="child-wrap">
<p>子组件</p>
<p>数字:{count}</p>
<button onClick={() => addCount(count + 1)}>数字递增</button>
</div>
);
}
export default Child;
父组件:
import React from 'react'
function Home() {
const [count, setCount] = React.useState(12345)
return (
<div>
<button onClick={()=>setCount(count+1)}></button>
<p>子组件传过来的数字:{count}</p>
</div>
)
}
export default Home