[英]React - Interacting with the state from another component
我有一个简单的React计数器,它的h2显示从0开始的计数,并且具有三个按钮:递增1,递减1并重置计数。
在这个应用程序中,计数将成为状态,由于这是一个很小的示例,因此仅制作一个组件是有意义的,例如:
const body = document.querySelector("body");
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.incrementCount = this.incrementCount.bind(this);
this.reduceCount = this.reduceCount.bind(this);
this.resetCount = this.resetCount.bind(this);
}
incrementCount() {
this.setState({
count: this.state.count + 1
});
}
reduceCount() {
this.setState({
count: this.state.count - 1
});
}
resetCount() {
this.setState({
count: 0
});
}
render() {
return(
<div>
<Count count={this.state.count} />
<button onClick={this.incrementCount}>+1</button>
<button onClick={this.reduceCount}>-1</button>
<button onClick={this.resetCount}>Reset</button>
</div>
);
}
}
ReactDOM.render(
<Counter />, body
);
这样就可以了。
但是,React的目标之一是将UI拆分为组件,因此我想为按钮创建一个名为Action的单独组件,并为其中一个包含h2以及状态和那些动作按钮的Count组件。 问题是我无法在Action组件内为onClick事件创建函数,因为状态将在Counter组件中,并且存在何时使用this关键字开始乐趣。
尽管如此,我还是为此提出了一种解决方法,它通过以下方式将eventHandlers作为props传递:
const body = document.querySelector("body");
class Count extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>Count: {this.props.count}</h2>
}
}
class Action extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button onClick={this.props.increment}>+1</button>
<button onClick={this.props.reduce}>-1</button>
<button onClick={this.props.reset}>Réinitialiser</button>
</div>
);
}
}
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.incrementCount = this.incrementCount.bind(this);
this.reduceCount = this.reduceCount.bind(this);
this.resetCount = this.resetCount.bind(this);
}
incrementCount() {
this.setState({
count: this.state.count + 1
});
}
reduceCount() {
this.setState({
count: this.state.count - 1
});
}
resetCount() {
this.setState({
count: 0
});
}
render() {
return(
<div>
<Count count={this.state.count} />
<Action
increment={this.incrementCount}
reduce={this.reduceCount}
reset={this.resetCount}
/>
</div>
);
}
}
ReactDOM.render(
<Counter />, body
);
这也有效,但是当我寻找此方法时,我没有看到提到的解决方法。 当然,我承认并不十分清楚如何寻找这个疑问。
这是一个好习惯吗? 我还有什么其他方法可以这样做?
如果您以更智能,最简单的方式来制造易于阅读且易于维护的组件,那么它们就足够了。
如果我重构您的组件,那么我将这样做: checkThisPen
创建函数时?
创建组件时?
注意:将ActionButton视为PureComponent或Fragment。 查看有关PureComponent和Fragment的文档以获取更多信息。 还使用ES6箭头功能incrementCount()
reduceCount()
resetCount()
这样您就不必在渲染时费心地绑定一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.