我正在寻找最简单的解决方案,将数据从子组件传递给他的父组件。
我听说过使用Context,传递属性或更新道具,但我不知道哪一个是最好的解决方案。
我正在构建一个管理界面,其中一个PageComponent包含一个带有表的ChildComponent,我可以在其中选择多行。我想向我的父PageComponent发送我在ChildComponent中选择的行号。
像这样的东西:
PageComponent:
<div className="App">
<EnhancedTable />
<h2>count 0</h2>
(count should be updated from child)
</div>
子组件:
const EnhancedTable = () => {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Click me {count}
</button>
)
};
我确定这是一件非常简单的事情,我不想使用redux。
您可以在父组件中创建一个方法,将其传递给子组件,并在每次子组件状态更改时从props调用它,从而将状态保持在子组件中。
const EnhancedTable = ({ parentCallback }) => {
const [count, setCount] = useState(0);
return (
<button onClick={() => {
const newValue = count + 1;
setCount(newValue);
parentCallback(newValue);
}}>
Click me {count}
</button>
)
};
class PageComponent extends React.Component {
callback = (count) => {
// do something with value in parent component, like save to state
}
render() {
return (
<div className="App">
<EnhancedTable parentCallback={this.callback} />
<h2>count 0</h2>
(count should be updated from child)
</div>
)
}
}
这些情况的一种常见技术是将lift the state up转换为需要使用状态的所有组件的第一个共同祖先(在本例中为PageComponent
),并将状态和状态改变函数作为道具传递给子组件。
例
const { useState } = React;
function PageComponent() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1)
}
return (
<div className="App">
<ChildComponent onClick={increment} count={count} />
<h2>count {count}</h2>
(count should be updated from child)
</div>
);
}
const ChildComponent = ({ onClick, count }) => {
return (
<button onClick={onClick}>
Click me {count}
</button>
)
};
ReactDOM.render(<PageComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>