[英]How to connect a button event to another React component?
I'm learning React and I'm trying to make a simple application: you click on a button and it increments a counter. 我正在学习React,并且试图创建一个简单的应用程序:单击一个按钮,它会增加一个计数器。 I've prepared two components,
ClickCounter
and ClickButton
, but I'm not sure how to connect them together. 我已经准备了两个组件,
ClickCounter
和ClickButton
,但是我不确定如何将它们连接在一起。 I've read different tutorials but they expect my components to be Parent/Child - is there something I'm completely missing from a architectural perspective? 我读过不同的教程,但他们希望我的组件是父级/子级-从体系结构的角度来看,我是否完全缺少某些东西?
class ClickCounter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <h1>{this.state.count}</h1>;
}
}
function ClickButton(props) {
function handleClick(e) {
e.preventDefault();
console.log("clicked");
// increment the ClickCounter..how?
}
return (
<button id="btn" onClick={handleClick}>Click me</button>
);
}
function Container() {
return (
<div>
<ClickCounter />
<ClickButton />
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<Container />, root);
A common technique for when two sibling components need to share some state is to lift the state up to the first common ancestor ( Container
in this case) and pass down the state and state-altering functions as props to the children. 当两个同级组件需要共享某个状态时,一种常见的技术是将状态提升到第一个公共祖先 (在这种情况下为
Container
)并将状态传递下来,并且将状态更改功能作为子项的支持。
Example 例
function ClickCounter(props) { return <h1>{props.count}</h1>; } function ClickButton(props) { return ( <button id="btn" onClick={props.handleClick}>Click me</button> ); } class Container extends React.Component { state = { count: 0 }; onClick = () => { this.setState(prevState => { return { count: prevState.count + 1 }; }); }; render() { return ( <div> <ClickCounter count={this.state.count} /> <ClickButton handleClick={this.onClick} /> </div> ); } } ReactDOM.render(<Container />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.