React子组件如何向父组件传值?
可以在父组件中创建一个方法,将其传递给子组件,并在每次子状态更改时从props调用它,并将状态保留在子组件中
代码案例
子组件:
import React, { useState } from "react";
function EnhancedTable({parentCallback}) {
const [count, setCount] = useState(0)
const clickCount = () => {
const newValue = count + 1;
setCount(newValue);
parentCallback(newValue)
}
return (
<button onClick={() => clickCount()}>
Click me {count} times
</button>
);
}
export default EnhancedTable;
父组件
App.js
import React, {useState} from "react";
import EnhancedTable from "./components/EnhancedTable";
function App() {
const [count, setCount] = useState(0)
const callback = (count) => {
console.log("count", count);
setCount(count);
}
return (
<div className="App">
<EnhancedTable parentCallback={callback} />
<h2>click {count} times</h2>
</div>
);
}
export default App;
运行结果: