在这个小例子中,父组件可以在自己组件中更改值来进行数值的加操作;而子组件可以获取父组件传来的数值,也可以调用父组件传来的方法进行数值的加操作,还可以更改自己组件中的值,传给父组件来进行数值的加操作。
目录结构:
App.jsx代码:
import React from "react";
import Father from "./page/Father";
export default function App() {
return (
<>
<Father />
</>
);
}
Father.jsx代码:
import React, { useState } from "react";
import Son from "./Son";
export default function Father() {
const [count, setCount] = useState(0);
const [value, setValue] = useState(1);
// 参数中的value是从子组件传来的
function fatherChange(value) {
// 此处的value可以使用到父组件中定义的value,也可以使用到子组件传来的value
setCount(count + value * 1);
}
// 通过选择更改父组件中value值
function fatherValueChange(e) {
setValue(e.target.value);
}
return (
<>
<h1>这是Father组件的内容</h1>
在父组件中更改相加的值:
<select onChange={fatherValueChange} value={value}>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<h3>这是父组件中的count:{count}</h3>
<button onClick={() => fatherChange(value)}>在父组件中更改count值</button>
<hr />
{/* 向子组件传递count值和fatherChange方法 */}
<Son count={count} fatherChange={fatherChange} />
</>
);
}
Son.jsx代码:
import React, { useState } from "react";
export default function Son(props) {
const { count, fatherChange } = props;
const [value, setValue] = useState(1);
// 调用父组件传来的方法,其中的value值是传递给父组件的
const sonChange = () => {
fatherChange(value);
};
const sonValueChange = (e) => {
setValue(e.target.value);
};
return (
<>
<h1>这是Son组件的内容</h1>
在子组件中更改相加的值:
<select onChange={sonValueChange} value={value}>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<h3>这是从Father组件传过来的count:{count}</h3>
<button onClick={sonChange}>使用父组件传来的方法来更改值</button>
</>
);
}